for循环浏览名称中带有空格的文件 [英] for loop through files with spaces in their names

查看:65
本文介绍了for循环浏览名称中带有空格的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录或压缩文件,每个文件包含一组XML文件我需要制作一个脚本,如果这些ZIP文件包含某个字符串,它将从这些ZIP文件中提取XML文件

I have a directory or zipped files, each containing a group of XML files I need to make a script that will extract XML files from those ZIPs if they contain a certain string

for z in `ls /path/to/archives/*.zip`
do for f in `unzip -l $z | grep 'xml' | awk -F" " '{print "$4" "$5}'`
  do r = $( unzip -p $z $f | grep $string )
    if [ '$r' != '' ]
    unzip $z $f
    fi
  done
done

运行此命令时,包含名为"my file.xml"的文件的zip文件A.zip导致循环将其处理为2个文件"my"和"file.xml"然后解压缩,然后尝试从A.zip提取文件my失败

When this runs, zip file A.zip containing a file called 'my file.xml' causes the loop to handle it as 2 files 'my' and 'file.xml' unzip then tries to extract file my from A.zip which fails

关于如何强制for循环不将文件名中的空格视为分隔符的任何想法?

Any ideas on how to force the for loop not to consider the space in the file name as a separator?

推荐答案

使用 unzip -Z1 选项代替 -l <​​/code>.每行输出一个文件,没有其他信息.您应该阅读其输出,而不是使用for进行循环,以防止单词分裂.您可能仍然对包含换行符的文件名有疑问(但是我无法压缩它们, $'a \ nb'被存储为 a ^ Jb 并提取为 ab ).

Use the -Z1 option of unzip instead of -l. It outputs one file per line with no additional information. You should read its output instead of loop over it with for to prevent word splitting. You might still have problems with filenames containing a newline (but I wasn't able to zip them, $'a\nb' was stored as a^Jb and extracted as ab).

此外,您的 if 缺少 then .

此外,不要解析 ls 的输出,您可以遍历全局文件掩码本身.

Also, don't parse the output of ls, you can iterate over the globbed file mask itself.

您无需检查 grep 是否输出任何内容,只需使用 -q 运行它并检查其退出状态即可.

You don't need to check that grep outputs anything, just run it with -q and check its exit status.

不要忘记将可能包含空格或其他特殊字符的变量双引号.

Don't forget to doublequote variables that might contain whitespace or other special characters.

for z in /path/to/archives/*.zip ; do
    while IFS= read -r f ;  do
        if unzip -p "$z" "$f" | grep -q "$string" ; then
            unzip "$z" "$f"
        fi
    done < <(unzip -Z1 "$z" '*.xml')
done

这篇关于for循环浏览名称中带有空格的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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