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

时间:2015-11-16 11:42:18

标签: bash shell grep

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

file: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是一个文件?

1 个答案:

答案 0 :(得分:2)

您可以在循环中阅读文件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"