2017-04-11 43 views
0

我有一個循環,在一系列的文本文件迭代(所有的形式爲name.txt):阻止循環遍歷與匹配模式的文件以嘗試遍歷文字模式?

for txt in *txt; do 
    sed -i '$ d' $txt 
done 

但每當沒有.txt文件中的目錄,我收到以下錯誤信息:

sed的:不能讀「* TXT」:沒有這樣的文件或目錄

+0

您的意思是否'sed的-i '$ d' $ txt' –

+0

是的,這是一個錯字。 – D1X

回答

0

您可以通過兩種方式解決此問題:

a)用它做任何事情

for txt in *txt; do 
    [[ -f "$txt" ]] || continue # skip if file doesn't exist or if it isn't a regular file 
    # your logic here 
done 

B之前檢查文件是否存在)使用shell選項shopt -s nullglob這將確保水珠變成了空當沒有匹配的文件

shopt -s nullglob 
for txt in *txt; do 
    # your logic here 
done 

參見:

0

這是因爲它是不匹配的任何文件,並留下「TXT」,而不是做你期望WH ich將跳過for循環。在某些實現(例如macOS)上,它會將字符串保留爲'* txt',並將變量txt設置爲* txt來運行for循環。在嘗試運行for-loop之前,您需要首先測試文件模式的存在。請參閱Check if a file exists with wildcard in shell script