2015-06-25 37 views
1

這是一個簡單的例子,希望能夠說明我的問題。沒有分詞的文件匹配?

我有一個腳本,需要一個參數作爲通配符使用。有時候這個通配符包含空格。我需要能夠使用通配符進行匹配,但分詞會導致它失敗。

例如,請考慮下面的示例文件:

$ ls -l "/home/me/dir with whitespace" 
total 0 
-rw-r--r-- 1 me  Domain Users 0 Jun 25 16:58 file_a.txt 
-rw-r--r-- 1 me  Domain Users 0 Jun 25 16:58 file_b.txt 

我的腳本 - 簡化使用硬編碼模式變量 - 是這樣的:

#!/bin/bash 

# Here this is hard coded, but normally it would be passed via parameter 
# For example: pattern="${1}" 
# The whitespace and wildcard can appear anywhere in the pattern 
pattern="/home/me/dir with whitespace/file_*.txt" 

# First attempt: without quoting 
ls -l ${pattern} 

# Result: word splitting AND globbing 
# ls: cannot access /home/me/dir: No such file or directory 
# ls: cannot access with: No such file or directory 
# ls: cannot access whitespace/file_*.txt: No such file or directory 


#################### 

# Second attempt: with quoting 
ls -l "${pattern}" 

# Result: no word splitting, no globbing 
# ls: cannot access /home/me/dir with whitespace/file_*.txt: No such file or directory 

有沒有一種方法,使通配符,但禁用分詞?
除了手動轉義我的模式中的空白外,還有其他選項嗎?

+0

非手動轉義空白怎麼樣? 'pattern =「$ {pattern ///\\}'。你需要轉義其他重要的字符(例如''''),所以我不建議單獨使用它! –

+0

是'''$ {pattern // \ * \''''''''''任何幫助?單引號整個字符串,然後用'*'替換'*'將它們放回到字符串外部。 '也是, –

+0

@TobySpeight - 我試圖逃避空格,它仍然是分詞的犧牲品,因爲'\\'是從字面上理解的,因爲它是在一個變量中,第二個建議既沒有用, '''字面意思 –

回答

0

我終於明白了!

訣竅是修改internal field separatorIFS)爲空。這樣可以防止在引號變量上進行分詞,直到IFS恢復爲舊值或直到它變爲未設置爲止。

例子:

$ pattern="/home/me/dir with whitespace/file_*.txt" 

$ ls -l $pattern 
ls: cannot access /home/me/dir: No such file or directory 
ls: cannot access with: No such file or directory 
ls: cannot access whitespace/file_*.txt: No such file or directory 

$ IFS="" 
$ ls -l $pattern 
-rw-r--r-- 1 me  Domain Users 0 Jun 26 09:14 /home/me/dir with whitespace/file_a.txt 
-rw-r--r-- 1 me  Domain Users 0 Jun 26 09:14 /home/me/dir with whitespace/file_b.txt 

$ unset IFS 
$ ls -l $pattern 
ls: cannot access /home/me/dir: No such file or directory 
ls: cannot access with: No such file or directory 
ls: cannot access whitespace/file_*.txt: No such file or directory 

我發現,你不能設置和使用IFSls艱辛的道路。例如,這不起作用:

$ IFS="" ls -l $pattern 

這是因爲該命令已經經過分詞IFS變化。

3

不要讓報價內水珠能夠擴展它:

pattern="/home/me/dir with whitespace/file_" 

ls -l "${pattern}"* 

編輯:基於編輯的問題

和評論你可以使用find

find . -path "./$pattern" -print0 | xargs -0 ls -l 
+0

我會的,但在實際的腳本中它是作爲參數傳遞的,而不是硬編碼的。例如,腳本使用'./script.sh「/ home/me/dir用whitespace/file_ * .txt「,並在腳本中執行'pattern =」$ {1}「'。空白和通配符可以出現在參數的任何位置,我不知道它們會在哪裏。 –

+0

ok check updated ans使用'find'。明天早上會回來看看,因爲這裏晚了。 – anubhava