我想在 some 中做一个 find ,并对这个目录中的文件dir
做一个awk
,然后用每个结果替换原始文件。
find dir | xargs cat | awk ... | mv ... > filename
所以我需要最后一个命令中的文件名(find 找到的每个文件)。我怎样才能做到这一点?
我想在 some 中做一个 find ,并对这个目录中的文件dir
做一个awk
,然后用每个结果替换原始文件。
find dir | xargs cat | awk ... | mv ... > filename
所以我需要最后一个命令中的文件名(find 找到的每个文件)。我怎样才能做到这一点?
你可以做这样的事情(但我根本不推荐它)。
find dir -print0 |
xargs -0 -n 2 awk -v OFS='\0' '<process the input and write to temporary file>
END {print "temporaryfile", FILENAME}' |
xargs -0 -n 2 mv
这一次将文件awk
直接传递给两个(这避免了原始文件的问题,其中cat
将同时获得数百个(可能更多)文件作为参数,并一次通过标准输入吐出它们的所有内容,awk
从而丢失它们各自的内容和完全文件名)。
然后它将awk
处理后的输出写入一个临时文件,然后输出临时文件名和原始文件名,并在xargs
其中提取它们(再次一次两个)并mv
在临时文件/原始文件名对上运行。
正如我在一开始所说的那样,这是一种可怕的方法。
如果您有足够新的版本GNU awk
(版本 4.1.0 或更高版本),那么您可以使用-i
(就地)参数awk
并使用(我相信):
find dir | xargs awk -i '......'
否则,我将使用Bash FAQ 001while
中的表单循环逐行读取输出并在循环中对其进行操作。find
我会使用一个循环,例如:
for filename in `find . -name "*test_file*" -print0 | xargs -0`
do
# some processing, then
echo "what you like" > "$filename"
done
编辑:如评论中所述,由于循环-print0 | xargs -0
而失去了好处。for
并且包含空格的文件名仍未正确处理。
以下while
循环也不会处理不寻常的文件名(很高兴知道它,尽管它不在问题中),但至少具有标准空格的文件名,因此它确实更好地工作:
find . -name "*test*file*" -print > files_list
while IFS= read -r filename
do
# some process
echo "what you like" > "$filename"
done < files_list