2015-04-03 60 views
2

我試圖cat文件名爲file sth.txt。當我寫如何在BASH中用文件名中的空格創建文件?

cat "file sth.txt" 

它很好用。

當我保存file sth.txt爲可變file和我執行

cat "$file" 

系統寫入

cat: file: No such file or directory 
cat: sth.txt: No such file or directory 

我想cat文件與變量,並在它不止一個文件名。對於沒有空間的文件名,它的作品。任何人都可以給我一些建議嗎?

+0

你使用'cat「$ file」'還是'cat $ file'?因爲引用的版本應該可以正常工作。 – 2015-04-03 17:51:52

+0

如果我在變量中有多個文件,那麼這是行不通的。我該怎麼做? – 2015-04-03 18:11:57

+0

如果您的變量包含多個文件名,那麼您不能在名稱中使用空格支持文件。不要在同一個變量中放置多個文件名。使用一個數組或多個參數。 – 2015-04-03 18:13:14

回答

0

試試這個,這是Mac OS X的終端處理這種情況的方式。

cat /path/to/file\ sth.txt 

你可以做同樣的腳本

sh script.sh /path/to/file\ sth.txt 
+0

我得到文件名作爲腳本的參數。我有1美元。 文件名是「文件sth.txt」。 – 2015-04-03 17:44:34

3

你有這樣的變量分配:

file="file sth.txt" 

或者:

file="$1" 
+1

這不起作用。它給我寫了同樣的錯誤。 – 2015-04-03 17:46:33

+1

它適合我。你怎麼稱呼你的劇本? – 2015-04-03 17:51:15

0

使用陣列:

# Put all your filenames in an array 
arr=("file sth.txt") # Quotes necessary 
arr+=("$1")   # Quotes necessary if $1 contains whitespaces 
arr+=("foo.txt") 

# Expand each element of the array as a separate argument to cat 
cat "${arr[@]}"  # Quotes necessary 

如果您發現自己依賴字詞拆分(即,在命令行上展開的變量被它們包含的空白分割爲多個參數的事實),使用數組通常會更好。

相關問題