Results 1 to 4 of 4
Hi everyone,
I am trying to learn G/AWK and was wondering if anyone could help me with the following:
I have an input file "numbers.txt" with 3 lines of text:
...
- 10-15-2009 #1Just Joined!
- Join Date
- Oct 2009
- Posts
- 3
G/AWK and Multiple Input Files
Hi everyone,
I am trying to learn G/AWK and was wondering if anyone could help me with the following:
I have an input file "numbers.txt" with 3 lines of text:
ONE TWO THREE FOUR FIVE
1 2 3 4 5
one two three four five
I have another file "columns wanted" with 3 lines specifying the columns I want to extract:
1
3
5
What I want to do is write a script that will return columns 1 3 and 5 from numbers.txt but I don't seem to be able to figure out how to go about doing this.
Could someone please give me some pointers or show me a resource that explains how to do this kind of thing - AND YES - I have tried google!
Many thanks.
MB.
- 10-15-2009 #2And if the numbers in the columns file are not ordered and you want to preserve their order, for example:Code:
awk 'NR == FNR { cols[$1]; next } { for (i=1; i<=NF; i++) if (i in cols) printf "%s", $i (i == NF ? RS : FS) }' columns_wanted numbers.txt
Code:3 1 5
Code:awk 'NR == FNR { t[++c] = $1; next } { for (i=1; i<=c; i++ ) printf "%s", $t[i] (i == c ? RS : FS) }' columns_wanted numbers.txt
- 10-16-2009 #3Just Joined!
- Join Date
- Oct 2009
- Posts
- 3
Hi Radoulov,
Thanks very much for your response. I have been working through it and it works well.
However, I am now trying to get that output into an output file. When I try and do this using:
The output looks like this:Code:NR == FNR { cols[$1]; next } { for (i=1; i<=NF; i++) if (i in cols) print $i (i == NF ? RS : FS) > "out" }
ONE
1
one
THREE
3
three
FIVE
5
five
I think I understand that this is because it is having to take into account the new file being generated when testing the conditional (i == NF ? RS : FS). How do I get round this so that the format of the file output is exactly the same as a the screen output?
Many thanks.
- 10-16-2009 #4


Reply With Quote
