[英]How can I use parameters in a bash script as subject text to grep?
我有一個簡單的bash腳本,該腳本接收帶有主題文本的文件,並逐行處理。
如果該行以某些字符開頭-請運行復合命令塊。 我正在嘗試使用grep測試行的模式(但會接受其他建議)。
#!/usr/bin/env bash
for i in "$@"
do
if grep "^M" $i # I want grep to "assume" $i was a file
# and test if the pattern "^M" is present
then
echo "This line started with an M: "$i
# command 1
# command 2
# etc
fi
done
D bar
M shell_test.sh
M another_file
然后運行腳本
cat subject_text.txt | xargs --delimiter="\n" ./matcher.sh
如何讓grep通過參數列表將每次迭代$i
視為$i
是文件?
您可以循環讀取文件Subject_text.txt
,並使用要檢查的文件名matcher.sh
:
while IFS= read -r _ file_name
do
./matcher.sh "$file_name"
done < "Subject_text.txt"
但是,現在我知道了,您在每行上都使用matcher.sh
。 請注意,以每行作為參數調用腳本有點過分。
如何正常循環文件並執行grep
呢?
#!/usr/bin/env bash
file=$1
while IFS= read -r line
do
if grep "^M" <<< "$line" # I want grep to "assume" $i was a file
# and test if the pattern "^M" is present
then
echo "This line started with an M: $i"
# command 1
# command 2
# etc
fi
done < "$file"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.