Is there an array version of $1...$NF in awk? -


consider following function in public domain.

function join(array, start, end, sep, result, i) {     if (sep == "")        sep = " "     else if (sep == subsep) # magic value        sep = ""     result = array[start]     (i = start + 1; <= end; i++)         result = result sep array[i]     return result } 

i use function join contiguous columns such $2, $3, $4 start , end ranges variables.

however, in order this, must first convert fields array using loop following.

for (i = 1; <= nf; i++) {     a[i] = $i     } 

or shorter version, @stevenpenny mentioned.

split($0, a) 

unfortunately both approaches require creation of new variable.

does awk have built-in way of accessing columns array above manual conversions not necessary?

no such array defined in posix awk (the array type special variables argv , environ).

none exists in gawk either, though adds procinfo, symtab , functab special arrays. can check defined variables , types @ runtime using symtab array (gawk-4.1.0 feature):

begin { procinfo["sorted_in"]="@ind_str_asc" }  # automagic sort "in" { print $0 } end   { (ss in symtab) printf("%-12s: %s\n",procinfo["identifiers"][ss],ss)  } 

(though find symtab , functab missing list, , missing --dump-variables too, treated specially design). gawk offers few standard loadable extensions, none implements feature though (and given dynamic relation ship between $0, $1..., nf , ofs, array had same functionality little tricky implement).

as suggested jidder, 1 work-around skip array altogether , use fields. there's nothing special field names, variable $n can used same literal $1 (just take care use braces precedence in expressions $(nf-1). here's fjoin function works on fields rather array:

function fjoin(start,end,sep,    result,ii) {     if (sep=="") sep=" "     else if (sep==subsep) sep =""     result=$start     (ii=start+1; ii<=end; ii++)          result=result sep $ii     return result }  { print "2,4: " fjoin(2,4,":") } 

(this not treat $0 special case)

or use split() , happy, gawk @ least guarantees behaves identically field splitting (assuming none of fs, fieldwidths , possibly ignorecase being modified change behaviour).


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -