Link to home
Start Free TrialLog in
Avatar of infa007
infa007

asked on

How to use AWK/SED to insert a line?

I have a file that looks like this:

Mary=Ann
Ann=Mary
Fake=Fake

Joe=John
Doe=Doe



I want to find Fake=Fake and insert another line before it. This change then needs to be written back to the same file. The replacement value is in a variable, say, $__changes

I have been trying sed but for some reason it creates a 0byte file if the source and target files are the same. I am ok if you can provide an awk solution.

__changes='$1.something'

cat 'file1.txt' | sed '
/Fake=FakeX/ i\
$__changes
' > 'file1.txt'

This doesn't work if I try a variable in the replacement text.

Please note I need to insert before only the first instance of the match.

Thanks for your help.
Avatar of ozo
ozo
Flag of United States of America image

>'file1.txt
opens and clears the output before sed runs
try sed -i
sed -i.bak -e '/Fake=Fake/ i\
'$__changes'
'  file1.txt
Avatar of infa007
infa007

ASKER

I get an error: sed: Not a recognized flag: i
ASKER CERTIFIED SOLUTION
Avatar of gisellla_igr
gisellla_igr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of infa007

ASKER

Thanks, exactly what I wanted!