[英]Whitespace in filenames in shell script
我有一個處理某些文件的Shell腳本。 問題是文件名中可能會有空格,我這樣做了:
#!/bin/sh
FILE=`echo $FILE | sed -e 's/[[:space:]]/\\ /g'`
cat $FILE
因此,變量FILE
是從其他程序傳入的文件名。 它可能包含空格。 我使用sed
使用\\
來轉義空格,以使命令行實用程序能夠對其進行處理。
問題是它不起作用。 echo $FILE | sed -e 's/[[:space:]]/\\\\ /g'
echo $FILE | sed -e 's/[[:space:]]/\\\\ /g'
本身可以正常工作,但是當分配給FILE
,轉義字符\\
再次消失。 結果, cat
會將其解釋為1個以上的參數。 我想知道為什么會這樣嗎? 反正有避免的方法嗎? 還有,如果有多個空格,說some terrible file.txt
,應將其替換為some\\ \\ \\ terrible\\ \\ file.txt
。 謝謝。
請勿嘗試在數據中放入轉義字符-它們僅作為語法而受到尊重(也就是說,反斜杠在源代碼中才有意義,而不是在數據中)。
也就是說,以下內容完全可以正常工作:
file='some terrible file.txt'
cat "$file"
...同樣,如果名稱來自全局結果或類似結果:
# this operates in a temporary directory to not change the filesystem you're running it in
tempdir=$(mktemp -d "${TMPDIR:-/tmp}/testdir.XXXXXX") && (
cd "$tempdir" || exit
echo 'example' >'some terrible file.txt'
for file in *.txt; do
printf 'Found file %q with the following contents:\n' "$file"
cat "$file"
done
rm -rf "$tempdir"
)
不要讓它變得比現在更復雜。
cat "$FILE"
這就是您所需要的。 注意變量周圍的引號。 它們防止變量在空白處擴展和分割。 您應該始終像這樣編寫Shell程序。 除非您確實希望shell擴展它們,否則請始終在所有變量周圍加上引號。
for i in $pattern; do
沒關系
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.