11

I've got a text file, and using Bash I wish to insert text into into a specific line.

Text to be inserted for example is !comment: http://www.test.com into line 5

!aaaa
!bbbb
!cccc
!dddd
!eeee
!ffff

becomes,

!aaaa
!bbbb
!cccc
!dddd
!comment: http://www.test.com
!eeee
!ffff
phuclv
  • 37,963
  • 15
  • 156
  • 475
user349418
  • 2,107
  • 4
  • 18
  • 14
  • Are you trying to do it in place for a large number of files? Or once for a single file? – MJB Jul 17 '10 at 23:40

4 Answers4

21
sed '4a\
!comment: http://www.test.com' file.txt > result.txt

i inserts before the current line, a appends after the line.

Anders
  • 6,188
  • 4
  • 26
  • 31
  • what does the 4a mean? – m4l490n Nov 09 '17 at 17:18
  • I'm curious why this doesn't work (without a new line after \ ): `sed '4a\!comment: http://www.test.com' file.txt > result.txt` I get the following error: `extra characters after \ at the end of a command` – sdc May 06 '18 at 18:14
  • 1
    Looks like sed requires an explicit newline or `\'$'\n`. Reference - https://stackoverflow.com/questions/8991275/escaping-newlines-in-sed-replacement-string#comment-11267604 – sdc May 06 '18 at 18:37
  • Thank you! An excellent way to insert license headers in XML files in a compliant way (nothing shall come before XML preamble), for example https://gist.github.com/berezovskyi/467320e305871498d0acdc32c6f269a2 – berezovskyi Oct 30 '20 at 16:45
  • @m4l490n I suppose `4a` means "4 after" (place the text after the 4th line on line 5). It worked in my case. Be aware that if you need to run the same command multiple times, the previous string does not get replaced, it just moves one line further (line 6 in our case). – DimiDak May 09 '23 at 17:41
4

you can use awk as well

$ awk 'NR==5{$0="!comment: http://www.test.com\n"$0}1' file
!aaaa
!bbbb
!cccc
!dddd
!comment: http://www.test.com
!eeee
!ffff
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
2

Using man 1 ed (which reads entire file into memory and performs in-place file editing without previous backup):

# cf. http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
line='!comment: http://www.test.com'
#printf '%s\n' H '/!eeee/i' "$line" . wq | ed -s file
printf '%s\n' H 5i "$line" . wq | ed -s file
JackIT
  • 21
  • 1
0

You can edit the file in place and add the string (let's say cookie) in the line you want with:

sed -i '5i\cookie' MyFile

Please be aware that:

  1. The line has to already exist in the file even if empty.
  2. If you use the command multiple times, the old string does not get deleted in order to be replaced by the new one. It moves one line further.
DimiDak
  • 4,820
  • 2
  • 26
  • 32