Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retrieving related information 1

Status
Not open for further replies.

ddrillich

Technical User
Jun 11, 2003
546
US
Good Day,

I have a config file that has a segment which looks like -

Code:
[Database1]
Name=Sports
ExpireIntoDatabase=SportArchive

[Database2]
Name=Entertainment

I need to grep, let's say, for Sports and return the corresponding DB name, in this case, Database1. I can assume safely that the DB line is one above the Name=Sports line.

Any thoughts?

Regards,
Dan
 
Hi

Just because you asked for :
Code:
grep -A 1 -F '[Database1]' /input/file | grep -v -F '[Database1]'
Otherwise [tt]awk[/tt] or [tt]sed[/tt] is much suitable for the task :
Code:
awk -F= '$0~/\[.*\]/{s=0}$0=="[Database1]"{s=1}s&&$1=="Name"{print$2}' /input/file

[gray]# or[/gray]

sed -n '/\[Database1\]/,/\[.*\]/s/^Name=//p' /input/file
With the [tt]awk[/tt] and [tt]sed[/tt] solutions the Name key can be anywhere in the given section and outputs only the value part.

Tested with GNU [tt]grep[/tt], [tt]gawk[/tt], [tt]mawk[/tt] and GNU [tt]sed[/tt].

Feherke.
 
Many thanks feherke.

Not sure if I was clear enough. All that I have up-front is Sports, from there I would like to extract the DB name in the line above. In this case - Database1.

Regards,
Dan
 
Hi

Oops. Then the code changes abit, but my other comments are still valid :
Code:
grep -B 1 -F 'Name=Sports' /input/file | grep -v -F 'Name=Sports'

[gray]# or[/gray]

awk -F= '$2=="Sports"{print p}/^\[.*\]/{gsub(/[\[\]]/,"");p=$0}' /input/file

[gray]# or[/gray]

sed -n '/^Name=Sports/{g;s/[][]//g;p};/^\[.*\]/h' /input/file

Feherke.
 
About the lovely -

Code:
sed -n '/^Name=Sports/{g;s/[][]//g;p};/^\[.*\]/h' /input/file

How can I replace Sports with a variable?

Regards,
Dan

 
You can just change the type of quotes and insert your variable:

Code:
sed -n "/^Name=$VARIABLE/{g;s/[][]//g;p};/^\[.*\]/h" /input/file

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top