Operating System - HP-UX
1833059 Members
2430 Online
110049 Solutions
New Discussion

Quick Script Command to Find/Insert a line

 
SOLVED
Go to solution
Tommy_6
Regular Advisor

Quick Script Command to Find/Insert a line

Good Morning eveyrone,
I'm looking for some quick expertise with sed/awk or anything other command that might work for me. I need to search a text file for "echo $x", each time "echo $x" is found, I need to insert "echo $y" on the line below it.

Thank you in advance!!!

Tommy
5 REPLIES 5
Rodney Hills
Honored Contributor
Solution

Re: Quick Script Command to Find/Insert a line

How about-

perl -i -n -e 'print $_; print "echo \$y\n" if /^echo \$x/;' yourfile.txt

This will update the file "yourfile.txt" with the additional "echo $y" lines.

HTH

-- Rod Hills
There be dragons...
Muthukumar_5
Honored Contributor

Re: Quick Script Command to Find/Insert a line

We can do it with sed easily as,

-- test.file --
itrc forums
test log entry to test
HELLO
bye for now
test will be thhere
HELLO
it is a test for log test
test over

If you want to put HAI below to HELLO then,

sed -e 's/^HELLO$/HELLO\
HAI/g' test.file

It will do that change.
Easy to suggest when don't know about the problem!
Muthukumar_5
Honored Contributor

Re: Quick Script Command to Find/Insert a line

We can do this using awk program too as,

--- test.log ---
itrc forums
test log entry to test
HELLO
bye for now
test will be thhere
it is a test for log test
HELLO
test over

To insert BYE after the pattern HELLO then,

awk '{ if ($0 == "HELLO" print $1 "\nBYE"
else $0 }' test.log

Easy to suggest when don't know about the problem!
H.Merijn Brand (procura
Honored Contributor

Re: Quick Script Command to Find/Insert a line

Why nor even shorter

# perl -pi -e'm/\becho\s*\$x\b/&&s/$/\necho \$y/' your_file

it is even safe against not inserting after 'echo $xb' or after 'becho $x'

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Tommy_6
Regular Advisor

Re: Quick Script Command to Find/Insert a line

I cannot thank you enough for all you quick knowledge. I ended up using Rodney Hills' perl command.

Tommy