[英]How can I use parameters in a bash script as subject text to grep?
I have a simple bash script, which receives a file with subject text, and processes line by line. 我有一个简单的bash脚本,该脚本接收带有主题文本的文件,并逐行处理。
If the line begins with certain characters - then run block of compound commands. 如果该行以某些字符开头-请运行复合命令块。 I am trying to use grep to test the lines for patterns (but would accept other suggestions).
我正在尝试使用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
Then run script with 然后运行脚本
cat subject_text.txt | xargs --delimiter="\n" ./matcher.sh
How can I get grep to treat each iteration $i
through the parameter list as if $i
were a file? 如何让grep通过参数列表将每次迭代
$i
视为$i
是文件?
You can read the file Subject_text.txt
in a loop and feed matcher.sh
with the name of the file to check: 您可以循环读取文件
Subject_text.txt
,并使用要检查的文件名matcher.sh
:
while IFS= read -r _ file_name
do
./matcher.sh "$file_name"
done < "Subject_text.txt"
However, now that I see, you are using matcher.sh
over every line. 但是,现在我知道了,您在每行上都使用
matcher.sh
。 Note that calling a script with every single line as parameter is a bit overkilling. 请注意,以每行作为参数调用脚本有点过分。
What about looping over the file normally and performing the grep
? 如何正常循环文件并执行
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.