這是一個簡單的例子,希望能夠說明我的問題。沒有分詞的文件匹配?
我有一個腳本,需要一個參數作爲通配符使用。有時候這個通配符包含空格。我需要能夠使用通配符進行匹配,但分詞會導致它失敗。
例如,請考慮下面的示例文件:
$ 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
有沒有一種方法,使通配符,但禁用分詞?
除了手動轉義我的模式中的空白外,還有其他選項嗎?
非手動轉義空白怎麼樣? 'pattern =「$ {pattern ///\\}'。你需要轉義其他重要的字符(例如''''),所以我不建議單獨使用它! –
是'''$ {pattern // \ * \''''''''''任何幫助?單引號整個字符串,然後用'*'替換'*'將它們放回到字符串外部。 '也是, –
@TobySpeight - 我試圖逃避空格,它仍然是分詞的犧牲品,因爲'\\'是從字面上理解的,因爲它是在一個變量中,第二個建議既沒有用, '''字面意思 –