Operating System - HP-UX
1753899 Members
7694 Online
108809 Solutions
New Discussion юеВ

Re: How to select a string from a file

 
SOLVED
Go to solution
Kellogg Unix Team
Trusted Contributor

How to select a string from a file

I have a file (file1) containing unique numbers, that I want to use to extract information from another file (file2).
file1 has the following contents -
14
15
20
201
202

file2 has the following text -
RaidGroup ID 14 Logical Capacity 23456 Free Capacity 12345
RaidGroup ID 20 Logical Capacity 23456 Free Capacity 12341
RaidGroup ID 204 Logical Capacity 23456 Free Capacity 12342
RaidGroup ID 202 Logical Capacity 23456 Free Capacity 12343
RaidGroup ID 2 Logical Capacity 23456 Free Capacity 12344

For each entry in file1 (which is field 3 in file2), I have to extract Free Capacity from file2. How do I structure my query so that when I awk for 20, I don't get results for 202 & 204 as well.

for x in `cat file1`
do
awk '$3 ~ /$x/' file2|awk '{print $NF}'
# The above line also gives error
done

Thanks.
work is fun ! (my manager is standing behind me!!)
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: How to select a string from a file

Hi:

# awk -v x=20 '$3==x' file2
RaidGroup ID 20 Logical Capacity 23456 Free Capacity 12341

Regards!

...JRF...
Kellogg Unix Team
Trusted Contributor

Re: How to select a string from a file

Bull's Eye! Thanks JRF!

Here is the quick solution -

for x in `cat file1`
do
awk -v x=$x '$3==x' file2
done

Thanks again.
work is fun ! (my manager is standing behind me!!)
Steven Schweda
Honored Contributor

Re: How to select a string from a file

> [...] so that when I awk for 20, I don't
> get results for 202 & 204 as well.

Including some white space in your search
string can help, too.

dy # x=20

dy # grep "$x" file2
RaidGroup ID 20 Logical Capacity 23456 Free Capacity 12341
RaidGroup ID 204 Logical Capacity 23456 Free Capacity 12342
RaidGroup ID 202 Logical Capacity 23456 Free Capacity 12343

dy # grep " $x " file2
RaidGroup ID 20 Logical Capacity 23456 Free Capacity 12341