1

It might be trivial, but I am facing problem in using awk for simple purpose like printing first row in a file using tcl script. I used the following command inside tcl script:

awk '/manager/ {print $4}' sourcefile.txt

But it gives error :

extra characters after close braces

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 print the specific column of the row which contains the searched string; here the searched string is "manager" and output I want is 4th column, So, the required output:

45000
50000
47000

The awk command works well in the terminal; but shows error while I put it inside a file, and then execute the file.

I got the solution up to this. Thanks for answering!

One more doubt, Suppose I have value "manager" stored in a variable "var". And I want to search using that variable: can I use this?

awk {/$var/ {print $4}} sourcefile.txt

I am not able to find a way. The above command does not give me result.

0

2 Answers 2

2

replace single quotes with braces, so

awk {/manager/ {print $4}} sourcefile.txt

The single quote character (') has no special meaning in Tcl language. It's just an ordinary character. In Tcl, words splits on whitespace, so any literals or strings with whitespace should be quoted. There are two ways to quote strings. With braces and with quotation marks.

When quoting with braces, no substitutions are performed. Embedded braces may be escaped with a backslash, but note that the backslash is part of the string.

When quoting with double quotes, command, backslash and variable substitutions are processed.


Or you can also do all in Tcl language

0
1

this could be simply done in tcl

set fi [ open "file.txt" ]
set lines [split [read $fi] "\n"]
close $fi
foreach line $lines {
        if { [ regexp {^.+manager.+$} $line manager ] } {
                regexp {[0-9]+$} $manager account
                puts $account
        }
}

or more awk-like

foreach line $lines {
        set la [ split $line ]
        if { [ lindex $la 1 ] eq {manager}  } {
                puts [ lindex $la 3 ]
        }

}

note that list index start at 0 and awk's $4' is tcl [lindex $la 3]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .