Solaris: find -exec command pipe commandfind . -name "*.dat" -exec sh -c 'grep ID $1 | wc -l' {} {} \;
This find command will count the number of records in a each file by counting the keys. This is a simplistic example which assumes a hash type file structure where the text of the keys does not occure within data or other keys. The purpose of this example is to illustrate pipes within a find. Most would prefer the following code which produces the same result. find . -name "*.dat" -print | xargs grep -c ID | |||||
| Data_File_1.dat | Data_File_2.dat | ||||
|---|---|---|---|---|---|
ID: 1 Command: find ID: 2 Command: xargs |
ID: 1 Command: find ID: 2 Command: xargs ID: 3 Command: grep | ||||
| Sample find, execute, grep command pipe command | |||||
bash$ find . -name "*.dat" -exec sh -c 'grep ID $1 | wc -l' {} {} \;
3
2
bash$ sh -c 'grep ID $1 | wc -l' Data_File_2.dat Data_File_2.dat
3
bash$ sh -c 'grep ID $1 | wc -l' Data_File_1.dat Data_File_1.dat
2
| |||||
|
As we can see, the find command above is simply running the the two commands that follow it using -exec. The reason that the argument is passed it twice, Using {} {}, is to ensure that things will work if you simply try changing shells. The following code helps demonstrate this. | |||||
| Shell and Argument Positions | |||||
bash$ sh -c 'echo $1' argument_1 agrument_2
agrument_2
bash$ bash -c 'echo $1' argument_1 agrument_2
agrument_2
bash$ csh -c 'echo $1' argument_1 agrument_2
argument_1
bash$ find . -name "*.dat" -exec sh -c 'grep ID $1 | wc -l' {} {} \;
3
2
bash$ find . -name "*.dat" -exec csh -c 'grep ID $1 | wc -l' {} {} \;
3
2
bash$ find . -name "*.dat" -exec csh -c 'grep ID $1 | wc -l' {} \;
3
2
bash$ find . -name "*.dat" -exec sh -c 'grep ID $0 | wc -l' {} \;
3
2
bash$ find . -name "*.dat" -exec bash -c 'grep ID $0 | wc -l' {} \;
3
2
bash$ find . -name "*.dat" -print -exec csh -c 'grep ID $1 | wc -l' {} {} \;
./Data_File_2.dat
3
./Data_File_1.dat
2
bash$ find . -name "*.dat" -exec csh -c 'echo -n $1; grep ID $1 | wc -l' {} {} \;
./Data_File_2.dat 3
./Data_File_1.dat 2
| |||||
|
| |||||
| |||||