Reputation: 9
It might be trivial, but I am facing problem in using awk for simple purpose like printing row in a file using tcl script. I have variable var :
set var manager
sourcefile.txt:
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000
I want to put command inside tcl script (awk/grep) which use variable var to search for string in source file and then print the 4th column of the line containing the string. I don't want to search for manager directly, but using var . I used:
awk -v pat="$var" {$2 ~ pat {print $4 }} sorcefile.txt
But it is giving me error saying
awk: 'pat' argument to '-v' not in var=value form
Also inside tcl script:
awk '/manager/ {print $4}' sourcefile.txt
gives error, and
awk {/manager/ {print $4}} sourcefile.txt
works well So, the required output:
45000
50000
47000
The command I need to put it inside a file, and then execute the file.
Upvotes: 0
Views: 985
Reputation: 247250
It's the position of the quotes.
$ tclsh
% set var manager
manager
+% exec awk -v pat="$var" {$2 ~ pat {print $4}} sourcefile.txt
No output. Let's ask the shell to echo
the awk command instead of executing it:
% exec echo awk -v pat="$var" {$2 == pat {print $4}} sourcefile.txt
awk -v pat="manager" $2 == pat {print $4} sourcefile.txt
Note how the double quotes are part of the pattern there?
Let's move the double quotes a bit:
% exec echo awk -v "pat=$var" {$2 == pat {print $4}} sourcefile.txt
awk -v pat=manager $2 == pat {print $4} sourcefile.txt
Note how the quotes are gone? Let's execute it now:
% exec awk -v "pat=$var" {$2 == pat {print $4}} sourcefile.txt
45000
50000
47000
This relates to the Tcl rule for double quotes -- the opening quote must be the first character of a word.
In the first case, the awk pat
variable is literally "manager"
, and as none of the $2 values contains quotes, no matches occur.
Upvotes: 2
Reputation: 571
this could be simply done in tcl
set var ...
set fi [ open "file.txt" ]
set lines [split [read $fi] "\n"]
close $fi
foreach line $lines {
set la [ split $line ]
if { [ lindex $la 1 ] eq $var } {
puts [ lindex $la 3 ]
}
}
note that list index start at 0 and awk's $4
' is tcl [lindex $la 3]
Upvotes: 1