shellxargs

How to handle file name with space in it with bash


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:

  1. Could the symbol ^ be any symbol, like {}, or # as long as they are used in the same places as ^?
  2. I saw -ne is printed above each file name, why is that and how to fix it?
  3. It can't correctly handle the file name with space in it. How to correct that? Thanks!

Solution

  • 1. Following strictly your request

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

    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")"' \;
    

    2. XY Problem?

    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 {} +