我希望编辑一个非常大的文件(~500GB)中的第一行和最后一行。该怎么做?例如,第一行是:
-flag </begin>
我希望能够省略“-flag”这个选项。我尝试使用sed(如下所示)来编辑第一行,但是没有生效:
sed -i '1s/-flag <begin>/<begin>/g' file.txt
我希望编辑一个非常大的文件(~500GB)中的第一行和最后一行。该怎么做?例如,第一行是:
-flag </begin>
我希望能够省略“-flag”这个选项。我尝试使用sed(如下所示)来编辑第一行,但是没有生效:
sed -i '1s/-flag <begin>/<begin>/g' file.txt
我无法想到一种可以原地实现的方法(如果有,我很乐意听听!)
虽然不是一行代码,但你可以尝试这个:
# substitute the first line and exit
sed '1s/-flag \(.*\)/\1/;q' file > new
# add the rest of the file (probably quicker than sed)
tail -n +2 file >> new
# cut off the last line of the file
truncate -s $(( $(stat -c "%s" new) - $(tail -n 1 new | wc -c) )) new
# substitute the last line
tail -n 1 file | sed 's/-flag \(.*\)/\1/' >> new
truncate
,并且您可以在shell中进行算术运算(我的shell是bash
)。
truncate -s
通过计算文件总大小stat -c“%s”
与最后一行的长度之间的差来删除最后一行。-flag
)。dd
命令。由于 OP 的示例正在删除文本,因此整个文件的其余部分都需要被移动... - twalberg如果你只想在第一行中去掉-flag
(注意末尾的空格):
sed -i '1s/-flag //' file
sed -i '1s/.*/new first line/' file
sed -i '$s/.*/new last line/' file
要删除第一行
sed -i 1d yourfile.txt
删除最后一行
sed -i '$d' yourfile.txt