由于可能导致您的命令行超载,因此我不会执行for
循环。命令行的长度有限,如果你超载了它,它会简单地删除多余的数据而不给你任何警告。它可能工作,如果你的查找返回100文件。它可能工作,如果它返回1000个文件,但它可能会失败,如果你的查找返回1000个文件,你永远不会知道。
处理此问题的最佳方法是将查找管道传送到while读取语句中作为glenn jackman。
sed命令仅适用于标准输入和文件,但不能在文件名,所以如果你想你的Munge时间的文件名,你就必须做这样的事情:
$newname="$(echo $oldname | sed 's/old/new/')"
得到文件的新名称。 $()
构造执行命令并将命令的结果放在STDOUT上。
所以,你的脚本就会是这个样子:
find /home/devel/stuff/static/ -name "*.pdf" | while read $file
do
echo $file;
newfile="$(echo $file | sed -e 's/static/changethis/')"
newfile="$newfile.xml"
echo $newfile;
done
现在,因为你重命名文件的目录,你必须确保你做你的移动或复制之前所在的目录:
find /home/devel/stuff/static/ -name "*.pdf" | while read $file
do
echo $file;
newfile="$(echo $file | sed -e 's/static/changethis/')"
newfile="$newfile.xml"
echo $newfile;
#Check for directory and create it if it doesn't exist
$dirname=$(dirname "$newfile")
if [ ! -d "$dirname" ]
then
mkdir -p "$dirname"
fi
#Directory now exists, so you can do the move
mv "$file" "$newfile"
done
请注意用引号来处理文件名中有空格的情况。
顺便说一句,而不是做这样的:
if [ ! -d "$dirname" ]
then
mkdir -p "$dirname"
fi
你可以这样做:
[ -d "$dirname"] || mkdir -p "$dirname"
的||
手段,执行下面的命令只有在测试是不正确的。因此,如果[-d“$ dirname”]是错误语句(该目录不存在),则运行mkdir
。
当您看到shell脚本时,这是一个相当常见的快捷方式。
没有。我试图获取文件名,追加“.xml”并将其放在diff目录中 – Mark
@Mark为您更新了答案 –
@Mu Qiao:您的通配符扩展将会丢失静态目录中的任何.txt文件。 find命令不会。 –