?
Solved

How to use AWK/SED to insert a line?

Posted on 2008-10-01
5
Medium Priority
?
1,568 Views
Last Modified: 2013-12-26
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
Comment
Question by:infa007
  • 2
  • 2
5 Comments
 
LVL 85

Expert Comment

by:ozo
ID: 22613806
>'file1.txt
opens and clears the output before sed runs
try sed -i
0
 
LVL 85

Expert Comment

by:ozo
ID: 22613869
sed -i.bak -e '/Fake=Fake/ i\
'$__changes'
'  file1.txt
0
 

Author Comment

by:infa007
ID: 22615073
I get an error: sed: Not a recognized flag: i
0
 
LVL 1

Accepted Solution

by:
gisellla_igr earned 2000 total points
ID: 22615298
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
 

Author Closing Comment

by:infa007
ID: 31501945
Thanks, exactly what I wanted!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month16 days, 15 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question