在“find -exec"中多次使用当前文件名(“{}")? [英] Use current filename ("{}") multiple times in "find -exec"?

查看:26
本文介绍了在“find -exec"中多次使用当前文件名(“{}")?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多消息来源说 {} 的每个实例都将替换为通过 find 找到的文件名,但是当我尝试运行以下命令时,我只得到一个文本文件,其名称为.txt"

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.

推荐答案

试试:

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

但请注意,某些版本的 find 要求 {} 是一个不同的参数,否则不会将 {} 扩展为文件名.您可以通过以下方式解决这个问题:

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' {} ;

(此替代命令会将输出文件放在包含匹配文件的子目录中.如果需要,您可以通过重定向到 ${0#*/}

(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#*/}

问题是 find 没有做重定向,shell 是.您的命令完全等同于:

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.

如果实用程序名称或参数字符串包含两个字符 "{}" ,而不仅仅是两个字符 "{}" ,则由实现定义 find 是否替换这两个字符或使用字符串而不进行更改.

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.

这篇关于在“find -exec"中多次使用当前文件名(“{}")?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆