• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1575
  • Last Modified:

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.
0
infa007
Asked:
infa007
  • 2
  • 2
1 Solution
 
ozoCommented:
>'file1.txt
opens and clears the output before sed runs
try sed -i
0
 
ozoCommented:
sed -i.bak -e '/Fake=Fake/ i\
'$__changes'
'  file1.txt
0
 
infa007Author Commented:
I get an error: sed: Not a recognized flag: i
0
 
gisellla_igrCommented:
try this

file=file1.txt
tmpFile=${file}$$
__changes="nueva linea"
cat $file | sed "
/Fake=Fake/ i\\
$__changes
" > $tmpFile
mv $tmpFile $file

Open in new window

0
 
infa007Author Commented:
Thanks, exactly what I wanted!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now