[英]Bash. When I find a file using files=`find…`, then use a for loop “for file in $files”. How do I access the path to the found file?
files=`find C:/PATH/TO/DIRECTORY -name *.txt`
for file in $files; do
#need code to rename $file, by moving it into the same directory
eg. 例如。 $file was found in C:/PATH/TO/DIRECTORY/2014-05-08. $ file在C:/ PATH / TO / DIRECTORY / 2014-05-08中找到。 how do I rename $file to back to that directory and not to C:/PATH/TO/DIRECTORY? 如何将$ file重命名到该目录而不是C:/ PATH / TO / DIRECTORY?
You can use -execdir
option in find: 您可以在查找中使用-execdir
选项:
find C:/PATH/TO/DIRECTORY -name '*.txt' -execdir mv '{}' '{}'-new \;
As per man find
: 根据每个man find
:
-execdir utility [argument ...] ;
The -execdir primary is identical to the -exec primary with the exception that utility will be executed from the directory that holds the current file. -execdir主目录与-exec主目录相同,不同之处在于将从包含当前文件的目录中执行实用程序。
find C:/PATH/TO/DIRECTORY -name \*.txt | while read file
do
dir=$(dirname "$file")
base=$(basename "$file")
mv "$file" "$dir/new_file_name"
done
You would be better served by using this structure: 使用以下结构会更好地为您服务:
while read fname
do
....
done < <(find ...)
Or, if you're not using bash
: 或者,如果您不使用bash
:
find ... | while read fname
do
....
done
The problem with storing the output of find
in a variable, or even doing for fname in $(find ...)
, is with word splitting on whitespace. 将find
的输出存储在变量中,甚至for fname in $(find ...)
进行存储的问题是在空格上进行单词拆分。 The above structures still fail if you have a file name with a newline in it, since they assume that you have one file name per line, but they're better than what you have now. 如果其中的文件名带有换行符,则上述结构仍然会失败,因为它们假定每行只有一个文件名,但是它们比现在更好。
An even better solution would be something like this: 更好的解决方案是这样的:
find ... -print0 | xargs -0 -n1 -Ixxx somescript.sh "xxx"
But even that might have issues if filenames have quotes or other things in them. 但是,即使文件名中带有引号或其他内容,也可能会出现问题。
The bottom line is that parsing arbitrary data (which filenames can be) is hard... 底线是很难解析任意数据(可以是文件名)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.