在Linux的特定位置添加一行并输出到同一文件? [英] Add a line in a specific position with Linux and output to the same file?
问题描述
如何在file.txt中添加第三行:
How to add a third line in file.txt:
line 1
line 2
line 4
sed可以处理 sed'3iline 3'file.txt
,但是我想输出到同一文件.我尝试 sed'3iline 3'file.txt>>file.txt
无效.它确实添加了行,但是它复制了file.txt,我得到了:
sed could do with sed '3iline 3' file.txt
but I want to output to the same file.
I tried sed '3iline 3' file.txt >> file.txt
which didn't work. It did add the line but it duplicates file.txt, I got this:
line 1
line 2
line 4
line 1
line 2
line 3
line 4
推荐答案
执行此操作的唯一方法是写入第二个文件,然后替换原始文件.您只能追加到任意文件;您不能插入其中一个.
The only way to do this is to write to a second file, then replace the original. You can only append to an arbitrary file; you cannot insert into the middle of one.
t=$(mktemp)
sed '3iline 3' file.txt > "$t" && mv "$t" file.txt
如果您的 sed
版本支持该功能,则可以使用 -i
选项自动处理临时文件.
If your version of sed
supports it, you can use the -i
option to automate the handling of the temporary file.
sed -i '3iline 3' file.txt # GNU
sed -i "" '3iline 3 ' file.txt # BSD sed requires an argument for -i
这篇关于在Linux的特定位置添加一行并输出到同一文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!