How can I print columns defined by variable?

Bash shell questions
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

How can I print columns defined by variable?

Post by MigrationUser »

09 Nov 2010 15:01
atayyy



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?

----------------------------

#2 08 Dec 2010 07:28
yoonix


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

Code: Select all

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

----------------------------

#3 08 Dec 2010 07:30
yoonix


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

True knowledge is knowing that you know nothing

----------------------------

#4 08 Dec 2010 19:13
Simon Sheppard

^ you can edit your own posts with the EDIT button

----------------------------

#5 20 Jul 2011 12:59
flabdablet

Code: Select all

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
Post Reply