Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

sed

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
like image 592
ziulfer Avatar asked Sep 17 '25 21:09

ziulfer


1 Answers

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
like image 56
chepner Avatar answered Sep 20 '25 12:09

chepner