Reputation: 11
I have around 600 files named like the IP address of the machines they have information on and with a .dgt
extension. I'm trying to search a parameter in those files and extract 2 lines from those files if a given parameter is correct. I'm using a aix console and after some search I found the sed
command in here. I leave you with an example of my search.
sed -n -e '/XP/,$p' 181* > machines1
sed -e '/XP/,$d' 181* > machines1
To be more specific, in the diretory I have a file listing of all my enterprise machines and it goes like this:
181xxxxxxxxx.dgt
181xxxxxxxxx.dgt
181xxxxxxxxx.dgt
181xxxxxxxxx.dgt
and they contain information like this:
MachineName= M125EEE
...
...
...
CurrentIP=XXX.XXX.XXX.XXX
...
...
OS=XP
...
...
...
I'm trying to get a list of all machines that have XP installed, so I'm trying to extract the OS line and the MachineName line so I can obtain a file like this...
MachineName= M125EEE
OS=XP
MachineName= M125EEE
OS=XP
MachineName= M125EEF
OS=XP
MachineName= M125EEG
OS=XP
Upvotes: 1
Views: 150
Reputation: 70922
Edit:
This will do what requested, but simplier (shorter) than 1st version:
sed -ne '/^MachineName=/h;/^OS=XP/{x;G;p}' 181*dgt >machines
give the same as 1st following answer:
Fist answer
This would do the job:
sed -ne '/^MachineName=/{h};/^OS=/{/=XP/!d;x;G;p;d;h}' 181*.dgt >machines
cat machines
MachineName= M125EEE
OS=XP
MachineName= M125EEE
OS=XP
MachineName= M125EEF
OS=XP
MachineName= M125EEG
OS=XP
but if you don't need to print OS=XP
each time, as this is the only string matching, you could keep them out:
sed -ne '/^MachineName=/{h};/^OS=XP$/{g;p}' 181*.dgt >machines
cat machines
MachineName= M125EEE
MachineName= M125EEE
MachineName= M125EEF
MachineName= M125EEG
and if you want only machine names but no MachineName=
, you could:
sed -ne '/^MachineName=/{s/^.*= *//;h};/^OS=XP$/{g;p}' 181*.dgt >machines
cat machines
M125EEE
M125EEE
M125EEF
M125EEG
Upvotes: 1
Reputation: 11473
It is not as runtime efficient as some of the other solutions, but for such a small number of files, this simple to understand solution may be appropriate:
grep -h MachineName $(grep -l OS=XP 181*)
grep -l means only print the names of the files that match. We then use those files names as a list of files to search for the MachineName line (-h means suppress filenames).
Upvotes: 1
Reputation: 204154
Try this:
awk '
BEGIN{ FS=OFS="=" }
{ map[FILENAME,$1] = $2 }
END {
for (file in ARGV) {
if ( map[file,"OS"] == "XP" ) {
tag="MachineName"; print tag, map[file,tag]
tag="OS"; print tag, map[file,tag]
tag="CurrentIP"; print tag, map[file,tag]
}
}
}
' 181*
Make the simple, obvious tweaks to output whatever values you like...
Upvotes: 2