Add a line in a specific position with Linux and output to the same file?

点点圈 提交于 2021-01-28 06:30:23

问题


How to add a third line in file.txt:

             line 1
             line 2
             line 4

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

回答1:


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

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


来源:https://stackoverflow.com/questions/46431161/add-a-line-in-a-specific-position-with-linux-and-output-to-the-same-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!