我有一个包含 2000 行的文件。我使用以下内容每 100 行拆分文件。
split -l 100 file.txt outputfile.txt
我想在每个文件内容的末尾添加一个“FFFFFF”,在拆分之后我还想指定文件使用的扩展名,就像上面的命令一样,输出如下。
outputfile.txtxa, outputfile.txtxb etc...
我已经阅读了拆分的手册页并浏览了网页,但是我找不到解决方案。
任何建议表示赞赏。
For a one pass solution, you could use awk
like this:
awk 'NR%100==1 { ++i } { print $0 (NR%100==0 ? "\nFFFFFF" : "") > "outputfile" i ".txt" }' file.txt
Also, the advantage here is finer control over the output filenames to make them more pretty. Please let me know if you require something more fancy. Cheers.
Explanation for user1937:
If you are familiar with the modulo operator, NR%100==1
will return true for the 1st line, the 101st line, the 201st line, the 301st line etc. Each time it's true, the variable i
is incremented. Notice how an awk
statement is made up of condition/action blocks. So NR%100==1
is the condition and ++i
is the action. What you'll then notice (hopefully) is that the block that has the print action lacks a conditional. Therefore every line of input is being printed (all of the time). The value of i
simply determines which file the output is being printed to.
Another bit you may not be familiar with is: (NR%100==0 ? "\nFFFFFF" : "")
. This is a
ternary operator which is shorthand for: if (NR%100==0) print "\nFFFFFF"; else print "")
. HTH.
awk
code can be built using pattern/action statements in the form:
NR%100==1 # pattern1
{
++i # action1
}
{
print $0 ... # action2
}
As you can see, pattern1 only applies to action1. pattern1 does not apply to action2.
你不能单独使用 split 来做到这一点。此代码可能会有所帮助:
split -l 100 file.txt outputfile_
find . -name outputfile_\* -exec sh -c 'echo "FFFFFF" >> {} && mv {} {}.txt' \;
这将导致文件outputfile_aa.txt
等outputfileab.txt
,它们都将以FFFFFF
.
其工作原理如下:首先我们使用前缀拆分文件outputfile_
以生成文件outputfile_aa
等outputfile_ab
。然后我们调用find
命令将它们全部收集起来并使用它执行命令。有一个小问题是你不能在 find 命令中使用重定向,所以我们将把重定向包装到一个 shell 脚本中并使用sh
. 将{}
被每个单独的文件名替换(-exec
在find
的手册页中查找);因此,脚本将首先将FFFFFF
字符串附加到文件的末尾,然后重命名文件以添加txt
扩展名。