bash 脚本:执行这些操作的更优雅的方式:

bash 脚本:执行这些操作的更优雅的方式:

我有这三个文件:

文件.txt.7z = 5.4GB
文件1.txt.7z = 251M
文件2.txt.7z = 7.7M

它们是目录中唯一的文件:

$ tree
.
├── file.txt.7z
├── file-1.txt.7z
└── file-2.txt.7z

我想要

  • 解压缩文件
  • 将它们合并到一个文件中
  • 将合并后的文件拆分为 500,000 行的文件
  • 结果有许多带有“.txt”扩展名的文件

现在我是这样实现的:

p7zip -d "*.txt.7z"
cat file-1.txt >> file.txt
rm file-1.txt
cat file-2.txt >> file.txt
rm file-2.txt
split -l 500000 file.txt
for f in *; do mv "$f" "$f.txt"; done

我怎样才能以更优雅的方式实现这一目标?

答案1

7za+split解决方案(单管道):

7za e "*.7z" -so 2> /dev/null | split -l500000 --additional-suffix=".txt" --numeric-suffixes=1 - "file"

--7za选项:

  • e- 提取/解压缩档案

  • -so- 将内容写入STDOUT


--split选项:

  • --additional-suffix=".txt"- 将后缀附加.txt到所有生成的文件名

  • --numeric-suffixes=1- 使用从以下位置开始的数字后缀1

  • -(连字符)- 从 STDIN(标准输入)读取数据

  • "file"- 所有结果文件名的公共前缀


上述命令将生成具有以下命名格式的文件:file01.txtfile02.txt

答案2

您可以使用管道和解压后--filter的选项split

p7zip -d *.txt.7z
cat file.txt file-1.txt file-2.txt | split -l 500000 --filter='> $FILE.txt'
rm file*

这是以下的文档--filter option

‘--filter=COMMAND’
     With this option, rather than simply writing to each output file,
     write through a pipe to the specified shell COMMAND for each output
     file.  COMMAND should use the $FILE environment variable, which is
     set to a different output file name for each invocation of the
     command.  For example, imagine that you have a 1TiB compressed file
     that, if uncompressed, would be too large to reside on disk, yet
     you must split it into individually-compressed pieces of a more
     manageable size.  To do that, you might run this command:

          xz -dc BIG.xz | split -b200G --filter='xz > $FILE.xz' - big-

     Assuming a 10:1 compression ratio, that would create about fifty
     20GiB files with names ‘big-aa.xz’, ‘big-ab.xz’, ‘big-ac.xz’, etc.

如果您需要保留包含所有输出的文件,可以使用tee,它将标准输入复制到标准输出以及作为参数给出的文件。

cat file.txt file-1.txt file-2.txt |
    tee all.txt |
    split -l 50000 --filter='> $FILE.txt'

相关内容