I'm referring to the following command from the book "Linux shell scripting cookbook".
find . -name '*.txt' | xargs -I ^ sh -c "echo -ne '\n ^: '; grep arg ^"
And have the following questions:
^
be any symbol, like {}, or # as long as they are used in the same places as ^
?-ne
is printed above each file name, why is that and how to fix it?
- Could the symbol ^ be any symbol, like {}, or # as long as they are used in the same places as ^?
Don't use xargs
with recent find
tool!
- I saw -ne is printed above each file name, why is that and how to fix it?
Don't use echo
, prefer printf
!
- It can't correctly handle the file name with space in it
Use double quptes for handling spaces in shell.
Using find to exec shell script:
find . -name '*.txt' -exec sh -c 'fnam="{}";printf "%s: " "$fnam"; grep arg "$fnam"' \;
or
find . -name '*.txt' -exec sh -c 'fnam="{}";printf "%s: %s\n" "$fnam" "$(grep arg "$fnam")"' \;
or even better:
export pattern="arg"
find . -name '*.txt' -exec sh -c 'fnam="{}";\
printf "%s: %s\n" "$fnam" "$(grep "$pattern" "$fnam")"' \;
Are you simply searching for files that contain the word arg
Simply use grep -r
:
grep -r arg .
Or showing all .txt
files and which of them that contain the word arg:
find . -name '*.txt' -exec grep -c arg {} +