问题
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