user385411
user385411

Reputation: 81

Calling grep with mulitple variables pattern

how can I use multiple patterns with grep in tcl?

set finish [exec bash -c "cat /home/new.txt |grep \"$day\|$yesterday\" > /home/new_tmp.txt"]

it works in the bash console

day=26.01.2020
yesterday=26.01.2020
cat /home/new.txt |grep "$day\|$yesterday"

but with Tcl script, the file is empty.

Upvotes: 0

Views: 407

Answers (2)

Shawn
Shawn

Reputation: 52334

A general grep tip: Since you're searching for multiple fixed strings, not really regular expressions, you can tell grep that to get a more efficient approach (And fix the issue of . being treated as a metacharacter and not an exact match):

grep -F -e "$day" -e "$yesterday" /home/new.txt > /home/new_tmp.txt

Or just do it all in pure tcl instead of getting a shell involved?

set infile [open /home/new.txt r]
set outfile [open /home/new_tmp.txt w]
while {[gets $infile line] >= 0} {
    if {[string first $day $line] >= 0 || [string first $yesterday $line] >= 0} {
        puts $outfile $line
    }
}
close $infile
close $outfile

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137567

A first trial would be:

set from /home/new.txt
set to /home/new_tmp.txt

set day 26.01.2020
set yesterday 26.01.2020
# Did you mean these two to be the same?

catch {exec grep "$day|$yesterday" <$from >$to}
# Because grep returns non-zero if it doesn't find anything, which exec converts to an error

You don't actually need an external cat very often, either in Tcl or in Bash.

Be aware that grep matches . with any character.

Upvotes: 1

Related Questions