You are not logged in.

#1 09 Nov 2010 15:01

atayyy
Member
Registered: 09 Nov 2010
Posts: 1

How can I print columns defined by variable?

input file
a b c d e f
1 2 3 4 5 6

if var="1 5"
output will be
a e
1 5

if var="2 3 6"
output will be
b c f
2 3 6

How can I do that by awk?

Offline

#2 08 Dec 2010 07:28

yoonix
Member
Registered: 29 Nov 2010
Posts: 9

Re: How can I print columns defined by variable?

i suppose you can use 'echo' as an input and using split to load the value into a set.

echo $1 |
awk '# list the number
BEGIN {
        var = "a,b,c,d,e,f"
        split (var,numerals,",")
echo $1 |
awk '# list the number
BEGIN {
        var = "a,b,c,d,e,f"
        split (var,numerals,",")
}

# look for a number relevant to letter
$1 > 0 && $1 < 10 {
        print numerals[$1]
        exit
        }
{       print "inv var"
        exit
}' -

probably need more work though..


True knowledge is knowing that you know nothing

Offline

#3 08 Dec 2010 07:30

yoonix
Member
Registered: 29 Nov 2010
Posts: 9

Re: How can I print columns defined by variable?

sorry mistake in paste, just start from second 'echo' statement to last portion of the script.


True knowledge is knowing that you know nothing

Offline

#4 08 Dec 2010 19:13

Simon Sheppard
Admin
Registered: 27 Aug 2005
Posts: 1,130
Website

Re: How can I print columns defined by variable?

^ you can edit your own posts with the EDIT button

Offline

#5 20 Jul 2011 12:59

flabdablet
Member
Registered: 11 Jul 2011
Posts: 26

Re: How can I print columns defined by variable?

awk -v fields="1 5" '
BEGIN {
    columns = split(fields, selected)
}

columns {
    printf "%s", $selected[1]
    for (i = 2; i <= columns; i++) {
        printf "%s%s", OFS, $selected[i]
    }
    print ""
}
' /path/to/input/file

Offline

Board footer

Powered by