繁体   English   中英

如何在bash脚本中使用参数作为grep的主题文本?

[英]How can I use parameters in a bash script as subject text to grep?

我有一个简单的bash脚本,该脚本接收带有主题文本的文件,并逐行处理。
如果该行以某些字符开头-请运行复合命令块。 我正在尝试使用grep测试行的模式(但会接受其他建议)。

文件:matcher.sh

#!/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

Subject_text.txt

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM