Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
bash在文件中的每一行上执行多个grep_Bash_File_Loops_Grep - Fatal编程技术网

bash在文件中的每一行上执行多个grep

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 我以为结果会是

我想在一个文件的每一行上按顺序运行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
我以为结果会是:

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 b
grep
假设参数是一个文件,使用一个here字符串作为stdin
grep b输入变量“我想在文件中的每一行上按顺序运行2个不同的grep,以便它将按照输入文件中出现的顺序输出匹配项”,如果该行与两种模式都匹配,则最终将写入两次。这是有意的吗?在文件的每一行调用
grep
在很多行中都会很慢。考虑使用<代码> Bash < /C>内置的正则表达式匹配,或者组合正则表达式,这样您就可以使用一个调用“代码> GRP读取整个文件。
#! /bin/bash

cat temp.txt | while read line
do
  echo $line
  grep b <<< "$line"
done