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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extract data from a file depending on pattern on another 1

Status
Not open for further replies.

Josewr

Technical User
Feb 28, 2005
15
US
I have 2 files with equal number of rows and the value of the first column is the same on both:

file1: (columns 1, 2, 3, 4)
1 5 3 4
2 2 1 3
3 1 5 8
4 7 8 6
...

file2: (columns 1, 2, 3 , 4, 5)
1 1 0 0 1
2 1 1 0 0
3 1 1 0 0
4 0 0 0 1
...

I want to create another file from file1 depending of the pattern of columns 2, 3, 4 and 5 of file2.

Example: for a pattern 1100, file3 should be:

2 2 1 3
3 1 5 8
...

And for a pattern XXX1, file4 should be:

1 5 3 4
4 7 8 6
...
Thanks
 
Code:
BEGIN {
  if (ARGC != 4)
  { print "Usage:" >"/dev/stderr"
    print "awk -f filt.awk file1 file2 pat" \
      >"/dev/stderr"
    exit 9
  }
  pat = ARGV[3] ;  ARGC--
  # Swap 1st and 2nd argument.
  temp = ARGV[1] ; ARGV[1] = ARGV[2]
  ARGV[2] = temp
  gsub( /./, "[ \t]+&", pat )
  pat = pat "$"
}

NR==FNR { if ($0 ~ pat) a[$1] ; next }
$1 in a
[tt]awk -f filt.awk data1 data2 "1100"

2 2 1 3
3 1 5 8

awk -f filt.awk data1 data2 "...1"

1 5 3 4
4 7 8 6
[/tt]
 
Thanks for your fast reply, futurelet.

I should have specified also to print the output to a tab delimited file.

I tried placing print $0 > "Output.asc"
after pat = pat "$".

Then I tried before "$1 in a" and got only errors.

(As you can see, I am a newbie at AWK)

Thankd again. JoséWR
 
Thanks,

Now if I could understand what all that code is doing past exit 9.
I guess I need to read the man awk or nawk in more detail.

Josewr
 
Now if I could understand what all that code is doing past exit 9.
I guess I need to read the man awk or nawk in more detail.
For an introduction to Awk, see faq271-5564.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top