Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm extracting rows from a set of text files with awk. The files look like this:

1000    1    75
1000    2    76
1001    1    76
1001    2    80

I'm searching several directories of these with this command:

awk -F"\t" '$3 == "76" { print $1"\t"$2}' ../benchmark/*/labels.txt

awk is giving me the correct output:

1000    2
1001    1

Now for each found row I must execute a script passing these two numbers as parameters, like this:

./build.oct 1000    2

What's the correct way to do that? I don't really care about script console output (it produces files).

share|improve this question

3 Answers 3

up vote 3 down vote accepted

You can also use xargs (-l makes it run a separate command for each line):

timp@helez:~/tmp$ awk -F"\t" '$3 == "76" { print $1"\t"$2}' test.txt | xargs -l ./build.oct 
$1 is  1000  and $2 is  2
$1 is  1001  and $2 is  1

timp@helez:~/tmp$ cat test.txt
1000    1   75
1000    2   76
1001    1   76
1001    2   80
timp@helez:~/tmp$ cat build.oct
echo '$1 is ' $1 ' and $2 is ' $2

As suggested in the comments you can also simplify the awk command, since both awk and xargs split on both tabs and spaces:

timp@helez:~/tmp$ awk '$3 == "76" {print $1,$2}' test.txt | xargs -l ./build.oct
$1 is  1000  and $2 is  2
$1 is  1001  and $2 is  1
share|improve this answer
    
This one worked! :) Thanks. –  Kuroki Kaze Jun 18 at 8:17
1  
You can simplify it to print $1,$2 since xargs will split on space as well as on tab characters. –  Stéphane Chazelas Jun 18 at 8:57
    
@stéphane-chazelas, correct; I was following the example of the original asker, but it can be simplified. I'll add a note to my answer about the shorter version of the awk command. –  TimP Jun 18 at 21:23

This worked for me:

awk -F"\t" '$3 == "76" { printf "./build.oct %d %d\n", $1, $2}' \
../benchmark/*/labels.txt | bash
share|improve this answer
    
Because the awk output is interpreted as shell code, you may want to sanitise your input. Replacing the %s with %d would make it safer in the event someone has managed to sneak a ;rm -rf / in the input files. –  Stéphane Chazelas Jun 18 at 8:55
    
@StéphaneChazelas Good point, I edited my answer, thanks –  chaos Jun 18 at 9:02

Assuming that columns 1 and 2 won't have whitespace in its entries, you can also do:

awk -F"\t" '$3 == "76" { print $1"\t"$2}' ../benchmark/*/labels.txt |
    while read a b; do ./build.oct $a $b; done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.