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.
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.
sed -i.bak -e '/Fake=Fake/ i\
'$__changes'
' file1.txt
'$__changes'
' file1.txt
ASKER
I get an error: sed: Not a recognized flag: i
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks, exactly what I wanted!
opens and clears the output before sed runs
try sed -i