Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

shell - Use current filename ("{}") multiple times in "find -exec"?

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 is ".txt"

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

The goal was to create a text file with only the eighth column from each file found, and each text file will be named after its parent file. Something about that second set of {} is not replacing with the filename of each found file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...