3

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).

5

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
  • 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 '14 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 '14 at 21:23
2

This worked for me:

awk -F"\t" '$3 == "76" { printf "./build.oct %d %d\n", $1, $2}' \
../benchmark/*/labels.txt | bash
  • 1
    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 '14 at 8:55
  • @StéphaneChazelas Good point, I edited my answer, thanks – chaos Jun 18 '14 at 9:02
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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