bash - Setting awk to variable -
i have code looks this:
awk -f'|' '{if($1 in a)print "duplicate found:" $2 " , "a[$1];else a[$1]=$2 }' dump.txt
i need set $2 , a[$2] variable. how go doing this?
i taking file contains: value "|" filename , want set filename , value 2 different variables.
what mean set variables? these environment variables. in awk, variables start dollar sign , numeric reserved awk. these field values each line. example:
test.txt = line 1 line 2 line 3
the command awk '{print $4}' test.txt
print out fourth field:
$ awk '{print $4}' test.txt 1 2 3 $ awk '{print $3}' test.txt line line line
as can see: don't have set. they're automatically set awk.
if want set environment variables, can use -v
parameter
awk -v search="foo" '{ if (search = $1) { print "found string in record " nr }'
in above, search
awk variable set equal foo
.
since awk programming language, easier see what's going on correctly formatting program:
awk -f'|' '{ if($1 in a) { print "duplicate found:" $2 " , " a[$1] } else { a[$1] = $2 } }' dump.txt
the program taking each line. each line consists of 2 parts separated |
. appears first part in key , second part data. i've created text file looks this:
this a|test a|line moans for|anchovies whom moans for|anchovies a|test again
the first , last line should show duplicates
i took program , added few debug lines. me trace in program:
awk -f\| '{ if ($1 in a) { print "debug: in if clause" print "duplicate found:" $2 " , " a[$1] } else { print "debug: in else clause" a[$1] = $2 print "debug: a[" $1 "] = " a[$1] } print "debug: $1 = " $1 print "debug: $2 = " $2 "\n" }' test.txt
and, output
debug: in else clause debug: a[this a] = test debug: $1 = debug: $2 = test debug: in else clause debug: a[that a] = line debug: $1 = debug: $2 = line debug: in else clause debug: a[who moans for] = anchovies debug: $1 = moans debug: $2 = anchovies debug: in else clause debug: a[whom moans for] = anchovies debug: $1 = whom moans debug: $2 = anchovies debug: in if clause duplicate found: test again , test debug: $1 =this debug: $2 = test again
taking out debug lines:
awk -f\| '{ if ($1 in a) { print "duplicate found:" $2 " , " a[$1] } else { a[$1] = $2 } }' test.txt duplicate found: test again , test
as say:
it works on my computer
(rimshot)
seriously, program suppose doing, , see do? there errors? program appears work advertised.
Comments
Post a Comment