Use current filename (“{}”) multiple times in “find -exec”?

前端 未结 3 482
小蘑菇
小蘑菇 2020-12-08 19:08

Many sources say that every instance of {} will be replaced with the filename found through find, but when I try to run the following, I only get one text file and its name

相关标签:
3条回答
  • 2020-12-08 19:26
    find /directory -name "*pattern*" | xargs awk '{z=FILENAME".txt";print $8>z}'
    
    0 讨论(0)
  • 2020-12-08 19:27

    Try:

    find /directory -name "*pattern*" -exec sh -c 'cut -f8 {} > {}.txt' \;
    

    But be aware that some versions of find require {} to be a distinct argument, and will not expand {} to a filename otherwise. You can work around that with:

    find /directory -name "*pattern*" -exec sh -c 'cut -f8 $0 > $0.txt' {} \;
    

    (this alternate command will put the output file in the subdirectory which contains the matched file. If desired, you could avoid that by redirecting to ${0#*/}

    The issue is that find is not doing the redirection, the shell is. Your command is exactly equivalent to:

    # Sample of INCORRECT code
    find /directory -name "*pattern*" -exec cut -f8 {} \; > {}.txt
    

    Note the following from the standard:

    If more than one argument containing only the two characters "{}" is present, the behavior is unspecified.

    If a utility_name or argument string contains the two characters "{}" , but not just the two characters "{}" , it is implementation-defined whether find replaces those two characters or uses the string without change.

    0 讨论(0)
  • 2020-12-08 19:27

    To deal with the caveats that William Pursell mentioned in his answer, use the following:

    find /directory -name "*pattern*" -exec sh -c 'cut -f8 "$1" > "$1.txt"' x {} \;
    

    When you use sh -c, it gets the positional parameters from arguments following the string to execute. The extra x fills in $0, and the substituted filename will become $1.

    The double quotes allow this to work properly with filenames containing spaces and other special characters.

    0 讨论(0)
提交回复
热议问题