bash在文件中的每一行上执行多个grep
我想在一个文件的每一行上按顺序运行2个不同的grep,这样它就会按照输入文件中出现的顺序输出匹配项。我有一个名为temp.txt的简单文件,我将在本例中使用它。该文件的内容包括:bash在文件中的每一行上执行多个grep,bash,file,loops,grep,Bash,File,Loops,Grep,我想在一个文件的每一行上按顺序运行2个不同的grep,这样它就会按照输入文件中出现的顺序输出匹配项。我有一个名为temp.txt的简单文件,我将在本例中使用它。该文件的内容包括: $ cat temp.txt line1 a line2 b line3 c 我有以下代码,通过使用echo而不是第一个grep来简化代码 #! /bin/bash cat temp.txt | while read line do echo $line grep b $line done 我以为结果会是
$ cat temp.txt
line1 a
line2 b
line3 c
我有以下代码,通过使用echo而不是第一个grep来简化代码
#! /bin/bash
cat temp.txt | while read line
do
echo $line
grep b $line
done
我以为结果会是:
line1 a
line2 b
line2 b
line2 c
但我得到了以下输出:
$ ./debug.sh
line1 a
grep: line1: No such file or directory
grep: a: No such file or directory
line2 b
grep: line2: No such file or directory
grep: b: No such file or directory
line3 c
grep: line3: No such file or directory
grep: c: No such file or directory
您必须执行以下操作:
#! /bin/bash
while read line
do
echo "$line" | grep "b"
done < temp.txt
就你而言
grep b $line
试图对名为$line
的文件执行grep b
,该文件显然不存在
注意:读取时无需
cat
将文件和管道连接到:。。。完成
就可以了。也许您应该只运行一个grep
,但要查找两种模式:
grep 'pattern1\|pattern2' file.txt
您的脚本应该如下所示
#! /bin/bash
cat temp.txt | while read line
do
echo $line
grep b <<< "$line"
done
#/bin/bash
cat temp.txt |读取行时
做
回音$线
grep bgrep
假设参数是一个文件,使用一个here字符串作为stdingrep b输入变量“我想在文件中的每一行上按顺序运行2个不同的grep,以便它将按照输入文件中出现的顺序输出匹配项”,如果该行与两种模式都匹配,则最终将写入两次。这是有意的吗?在文件的每一行调用grep
在很多行中都会很慢。考虑使用<代码> Bash < /C>内置的正则表达式匹配,或者组合正则表达式,这样您就可以使用一个调用“代码> GRP读取整个文件。
#! /bin/bash
cat temp.txt | while read line
do
echo $line
grep b <<< "$line"
done