我想遍历一个文件列表。这个列表是一个find命令的结果,所以我想出了:

getlist() {
  for f in $(find . -iname "foo*")
  do
    echo "File found: $f"
    # do something useful
  done
}

这很好,除非文件名称中有空格:

$ ls
foo_bar_baz.txt
foo bar baz.txt

$ getlist
File found: foo_bar_baz.txt
File found: foo
File found: bar
File found: baz.txt

我能做些什么来避免空格分割?


当前回答

我真的很喜欢for循环和数组迭代,所以我想我会把这个答案添加到混合…

我也喜欢marchelbling愚蠢的文件示例。:)

$ mkdir test
$ cd test
$ touch "stupid file1"
$ touch "stupid file2"
$ touch "stupid   file 3"

在test目录中:

readarray -t arr <<< "`ls -A1`"

这将每个文件列表行添加到名为arr的bash数组中,并删除任何尾随换行符。

假设我们想给这些文件取一个更好的名字……

for i in ${!arr[@]}
do 
    newname=`echo "${arr[$i]}" | sed 's/stupid/smarter/; s/  */_/g'`; 
    mv "${arr[$i]}" "$newname"
done

$ {!arr[@]}扩展到0 1 2,因此"${arr[$i]}"是数组的第i个元素。变量周围的引号对于保留空格很重要。

结果是三个重命名的文件:

$ ls -1
smarter_file1
smarter_file2
smarter_file_3

其他回答

find . -iname "foo*" -print0 | xargs -L1 -0 echo "File found:"

你可以用基于行的迭代替换基于单词的迭代:

find . -iname "foo*" | while read f
do
    # ... loop body
done

我真的很喜欢for循环和数组迭代,所以我想我会把这个答案添加到混合…

我也喜欢marchelbling愚蠢的文件示例。:)

$ mkdir test
$ cd test
$ touch "stupid file1"
$ touch "stupid file2"
$ touch "stupid   file 3"

在test目录中:

readarray -t arr <<< "`ls -A1`"

这将每个文件列表行添加到名为arr的bash数组中,并删除任何尾随换行符。

假设我们想给这些文件取一个更好的名字……

for i in ${!arr[@]}
do 
    newname=`echo "${arr[$i]}" | sed 's/stupid/smarter/; s/  */_/g'`; 
    mv "${arr[$i]}" "$newname"
done

$ {!arr[@]}扩展到0 1 2,因此"${arr[$i]}"是数组的第i个元素。变量周围的引号对于保留空格很重要。

结果是三个重命名的文件:

$ ls -1
smarter_file1
smarter_file2
smarter_file_3

还有一个非常简单的解决方案:依赖bash globbing

$ mkdir test
$ cd test
$ touch "stupid file1"
$ touch "stupid file2"
$ touch "stupid   file 3"
$ ls
stupid   file 3  stupid file1     stupid file2
$ for file in *; do echo "file: '${file}'"; done
file: 'stupid   file 3'
file: 'stupid file1'
file: 'stupid file2'

注意,我不确定这个行为是默认的,但我在我的商店里没有看到任何特殊的设置,所以我会说它应该是“安全的”(在osx和ubuntu上测试过)。

我最近不得不处理一个类似的情况,我构建了一个FILES数组来遍历文件名:

eval FILES=($(find . -iname "foo*" -printf '"%p" '))

这里的想法是用双引号包围每个文件名,用空格分隔它们,并使用结果初始化FILES数组。 必须使用eval来正确计算find输出中的双引号,以初始化数组。

要遍历文件,只需执行:

for f in "${FILES[@]}"; do
    # Do something with $f
done