2011-12-30 27 views
33

我想遍歷文件列表而不關心文件名可能包含的字符,因此我使用由空字符分隔的列表。代碼將更好地解釋事情。通過Bash循環讀空分隔的字符串

# 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 

以下代碼在從文件讀取時有效,但需要從包含文本的變量中讀取。

while read -d $'\0' line ; do 
    # Code here 
done < /path/to/inputfile 
+1

我不認爲有可能將空字符存儲在bash變量中。至少,我從來沒有找到辦法做到這一點...... – 2011-12-30 18:25:20

回答

53

在bash,那麼你可以使用下面的字符串

while IFS= read -r -d '' line ; do 
    # Code here 
done <<<"$var" 

請注意,您應內嵌IFS=,只是使用-d ''但要確保有是「d」和第一單之間的空間-引用。另外,添加-r標誌來忽略轉義。

而且,這不是你的問題的一部分,但我可能會提出一個更好的方式使用find時候做你的腳本;它使用流程替換。

while IFS= read -r -d '' file; do 
    # Arbitrary operations on "$file" here 
done < <(find /some/path -type f -print0) 
+0

非常好,正是我所期待的。謝謝!我結束了使用你的第二個例子。 – Matthew 2011-12-30 17:30:57

+0

自設置-d標誌以來IFS的用途是什麼? – thisirs 2013-03-06 15:02:51

+4

@thisirs通過將IFS設置爲空字符串,將保留前導和尾隨空白字符。 – toxalot 2014-03-10 04:48:12