3

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
ziulfer
  • 1,339
  • 5
  • 18
  • 30
  • Only some implementations of `sed` (GNU sed and BSD sed AFAIK) support `-i` switch for "in-place" editing. – Kaushik Nayak Sep 26 '17 at 16:09
  • You can also play around with diamond `<>` operator in `Bash` if you feel brave: http://backreference.org/2011/01/29/in-place-editing-of-files/. See also this answer: https://stackoverflow.com/a/39143992/3691891 – Arkadiusz Drabczyk Sep 26 '17 at 16:57

1 Answers1

7

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
chepner
  • 497,756
  • 71
  • 530
  • 681