carol
carol

Reputation: 171

variable set used by awk in bash

whether I use colNb or $colNb, it doesn't work

export colNb=$(awk '{print NF}' file1 | sort -nu | tail -n 1)

awk '{for(i=3 ; i<colNb; i++) {printf("%s\t", $i)} print ""}' file1 | less

with $colNb, I get

awk: illegal field $(), name "colNb"
 input record number 1, file1
 source line number 1

and with colNb, I just get empty fields instead of the fields in file1

Upvotes: 2

Views: 5229

Answers (2)

Jotne
Jotne

Reputation: 41436

Do like this

awk '{for(i=3 ; i<c; i++) {printf("%s\t", $i)} print ""}' c="$colNb" file1 | less

You need to set variable outside awk with -v or after awk

Upvotes: 2

anubhava
anubhava

Reputation: 784878

Use -v option in awk to pass shell variables to awk:

awk -v colNb="$colNb" '{for(i=3 ; i<colNb; i++) {printf("%s\t", $i)} print ""}' file1 | less

Upvotes: 3

Related Questions