[英]How to delete certain words from files with shell script?
我必須從通過命令行作為參數給出的每個文件中刪除包含至少一個數字的每個單詞。 這是我的代碼:
while [ "$*" != "" ]; do
if [ ! -f $1 ]
then echo "$1 not file"
else
sed -ie "s/[^ ]*[0-9][^ ]*//g" $1
fi
shift
done
如果我只有一個文件,它會完美運行,但如果我有更多文件,它會為每個文件提供相同的結果。 在每個文件中運行腳本后,將得到第一個文件的結果。
有人可以告訴我我錯過了什么嗎?
編輯2:
這就是我現在正在運行的:
while [ "$#" -ne 0 ]; do
for file in "$@"; do
if [ ! -e "$file" ]; then
printf "file doesn't exist: %s\n" "$file"
continue;
fi
if [ ! -f "$file" ]; then
printf "not a file: %s\n" "$file"
continue;
fi
done
sed -i "s/[^ ]*[0-9][^ ]*//g" "$file"
done
我說的是 while 循環的 done 和 for 循環的 done; 但即使沒有,我的腳本也會繼續運行。
編輯:
基本上是一樣的,只是有點不同。 我必須從每個文件的每一行中刪除第二個和第四個單詞(單詞僅包含字母數字字符)。 它工作不正常,我找不到錯誤。 這是我的代碼:
while [ "$*" != "" ]; do
if [ ! -f $1 ]
then echo "$1 not file"
else
sed -ie 's/^\( *[^ ]+\) +[^ ]+\(.*\)/\1\2/
s/^\( *[^ ]+\)\( +[^ ]+\) +[^ ]+\(.*\)/\1\2\3/g' $1
fi
shift
done
while 循環條件應檢查是否沒有 arguments,如果有則應繼續。 所以正確的形式是
while [ "$#" -ne 0 ]; do
現在,您真正想要的是獲取每個參數並對其進行處理。 這自動意味着一個for 循環。 所以你真正應該做的是
for file in $@; do
現在,一個文件中可以有空格,因此獲取該文件名並檢查它是否真的是一個文件應該被引用,並且您還應該首先檢查是否存在
for file in "$@"; do
if [ ! -e "$file" ]; then
printf "file doesn't exist: %s\n" "$file"
continue;
fi
if [ ! -f "$file" ]; then
printf "not a file: %s\n" "$file"
continue;
fi
sed -i "s/[^ ]*[0-9][^ ]*//g" "$file"
done
我可以在sed
上進行更多擴展,其中-i
開關僅限於 GNU sed。 除此之外,您可能還希望保留該文件的備份,以防出現問題。
但我猜這是另一個話題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.