2

I want to output top 10 lines of AWK command in the list of files given by find, using this snippet:

$ find . -name "*.txt" -print -exec awk '$9 != ""'  \| head -n10 {} \;

Note also that I want to print out the file names being processed.

But why I get such error:

awk: cmd. line:2: fatal: cannot open file `|' for reading (No such file or directory)
./myfile.txt

What's the right way to do it?

I tried without backslash before the pipe. Still it gave an error:

find: missing argument to `-exec'
head: cannot open `{}' for reading: No such file or directory
head: cannot open `;' for reading: No such file or directory
Rubén
  • 34,714
  • 9
  • 70
  • 166
neversaint
  • 60,904
  • 137
  • 310
  • 477

5 Answers5

4

When running a command with find's -exec, you don't get all the nice shell things like the pipe operator (|). You can regain them by explicitly running a subshell if you like though, eg:

find . -name '*.txt' -exec /bin/sh -c "echo a text file called {} | head -n 15" \;

Anthony Towns
  • 2,864
  • 1
  • 19
  • 23
3

If you want to run an Awk program on every file from find that only prints the first 10 lines each time.

$ find . -name "*.txt" -print -exec awk '$9 != "" && n < 10 {print; n++}' {} \;
ashawley
  • 4,195
  • 1
  • 27
  • 40
2

Based on Ashawley's answer:

find . -name "*.txt" -print -exec awk '$9 != "" {print; if(NR > 9) exit; }' {} \;

It should perform better, as we exit awk after the 10th record.

MatthieuP
  • 1,116
  • 5
  • 12
1

You can do it this way too:

find . -name '*txt' -print -exec awk 'BEGIN {nl=1 ;print FILENAME} $9 !="" {if (nl<11) { print $0 ; nl = nl + 1 }}' {}  \;

without head.

Zsolt Botykai
  • 50,406
  • 14
  • 85
  • 110
1

Using awk only should work:

find . -name "*.txt" -print -exec awk '{if($9!=""&&n<11){print;n++}}' {} \;
mouviciel
  • 66,855
  • 13
  • 106
  • 140