我想迭代一个文件列表.这个列表是find
命令的结果,所以我想出了:
getlist() {
for f in $(find . -iname "foo*")
do
echo "File found: $f"
# do something useful
done
}
Run Code Online (Sandbox Code Playgroud)
没关系,除非文件名中有空格:
$ 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
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能避免空格分裂?
我想迭代一个文件列表,而不关心文件名可能包含哪些字符,所以我使用一个由空字符分隔的列表.代码将更好地解释事情.
# Set IFS to the null character to hopefully change the for..in
# delimiter from the space character (sadly does not appear to work).
IFS=$'\0'
# Get null delimited list of files
filelist="`find /some/path -type f -print0`"
# Iterate through list of files
for file in $filelist ; do
# Arbitrary operations on $file here
done
Run Code Online (Sandbox Code Playgroud)
从文件读取时,以下代码有效,但我需要从包含文本的变量中读取.
while read -d $'\0' line ; do
# Code here
done < /path/to/inputfile
Run Code Online (Sandbox Code Playgroud)