tags:

views:

72

answers:

3

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

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

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

Anders
A: 

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
A: 

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