1833756 Members
2821 Online
110063 Solutions
New Discussion

sed question

 
SOLVED
Go to solution
John McWilliams
Advisor

sed question

Hi All - I have a file that I want to add a line into. This line needs to be added after the line starting with the word "History".
I believe sed can do this but I cant figure out how to get it to work. Any ideas would be appreciated.
thanks John
4 REPLIES 4
Steven Sim Kok Leong
Honored Contributor

Re: sed question

Hi,

Your task can be accomplished easily with perl:

==
[root@cc0070 /root]# cat infile
abc
History
def
History abcdef abcdef
abc
abc
a History a b c d e
b History a b c d e
[root@cc0070 /root]# ./testperl
[root@cc0070 /root]# cat outfile
abc
History
INSERTED_TEXT
def
History abcdef abcdef
INSERTED_TEXT
abc
abc
a History a b c d e
b History a b c d e
You have new mail in /var/spool/mail/root
[root@cc0070 /root]# cat testperl
#!/usr/bin/perl

open (INFILE, "infile");
open (OUTFILE, ">outfile");
while ()
{
$_ =~s/^History(.*)/History\1\nINSERTED_TEXT/g;
print OUTFILE $_;
}
==

Hope this helps. Regards.

Steven Sim Kok Leong
Brainbench MVP for Unix Admin
http://www.brainbench.com

Bruce Regittko_1
Esteemed Contributor

Re: sed question

Hi,

To add 3 lines after all lines that begin with History:

sed -e '/^History/aline to add #1line to add #2line to add #3' file

Note the single quotes and the backslashes \. They are important.

If you have multiple History lines and only want to append after the first, it gets more complex and requires two sed commands (at least by me - sed gurus may be able to do it in one command).

sed -e '/^History/aline to add #1line to add #2line to add #3' -e '/^History/d' file > file.tmp

sed -e '1,/^History/d' file >> file.tmp

Disclaimer: I read the HP man pages but tested this on a Linux box. It *should* work on HP-UX.

--Bruce
www.stratech.com/training
Bruce Regittko_1
Esteemed Contributor
Solution

Re: sed question

Hi again,

Arrrgghh! Apparently the reply interface doesn't handle lines ending in a backslash well. The correctly formatted sed commands are in the attachment.

--Bruce
www.stratech.com/training
Tommy Palo
Trusted Contributor

Re: sed question

You can also do this with 'ed':

#!/usr/bin/ksh
cat - << EOF | ed -s file_to_edit
/History
+1
i
New Line of text
.
w
q
EOF
Keep it simple