【问题标题】:Issues in spaced filepaths with complex find loop具有复杂查找循环的间隔文件路径中的问题
【发布时间】:2014-07-14 20:38:23
【问题描述】:

标题应该说明一切,如果没有让我知道,我会更新问题。

代码

TYPE=('html?' 'jsp' 'php')
TYPE=$(printf "|%s" "${TYPE[@]}")

## will not except paths with spaces
for file in $(find -E * -type f -iregex ".*(${TYPE:1})") ; do 
    echo $file
done

在尝试包装时

## command substitution: line ~: syntax error near unexpected token `('
## command substitution: line ~: `find -E * -type f -iregex \".*(${TYPE:1})\")"'
for file in "$(find -E * -type f -iregex \".*(${TYPE:1})\")" ; do 
    echo $file
done

【问题讨论】:

标签: bash for-loop find


【解决方案1】:

你引用错了。正确的做法是:

for file in $(find -E * -type f -iregex ".*(${TYPE:1})"); do 

但如果您使用 bash,更好的方法是使用带有进程替换的 while 循环:

while IFS= read -r file; do
    echo "$file"
done < <(exec find -E * -type f -iregex ".*(${TYPE:1})")

find -E * -type f -iregex ".*(${TYPE:1})" | while IFS= read -r file; do 也可能适用,但它在子shell 上运行您的循环。变量的变化在退出后就丢失了。

此外,如果您使用的是 Bash 3.1 或更新版本,您可以使用 printf 的 -v 选项:

printf -v TYPE '|%s' "${TYPE[@]}"

【讨论】:

  • Hrm,好像没用,我的 Python 还在报错。 pastebin.com/tGfACpK3
  • @ehime 这当然不适合 Python。其他命令是什么?
  • 没关系,看起来 WHILE 工作得很好。接受并加 1。谢谢先生。
  • 我在上面的 pastebin 链接上添加了它,以防你想看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多