读取行并匹配模式

app*_*nic 8 bash read

我想不通。我需要查看文件中的每一行并检查它是否与变量中给出的单词匹配

我从命令读取开始,但我不知道在那之后我应该使用什么,我尝试过grep但我可能错误地使用了它。

while read line; do 
if [ $condition  ] ;then echo "ok" fi
done<file.txt
Run Code Online (Sandbox Code Playgroud)

dou*_*BTV 8

这是给你的一个快捷方式,我们正在做的就是

第 1 行:将文件读入变量时 line

第 2 行:匹配正则表达式,回显$line匹配单词“bird”的if 回显该行。在此 if 语句中执行您需要的任何操作。

第 3 行:while 循环结束,在文件中进行管道传输 foo.text

#!/bin/bash
while read line; do
  if [[ $line =~ bird ]] ; then echo $line; fi
done <foo.text
Run Code Online (Sandbox Code Playgroud)

请注意,“鸟”是一个正则表达式。这样您就可以将其替换为例如:bird.*word将同一行与正则表达式匹配。

用这样的文件试试,用foo.text内容调用:

my dog is brown
her cat is white
the bird is the word
Run Code Online (Sandbox Code Playgroud)


小智 5

更简单的方法是使用grep(或egrep)。

grep bird file.txt
Run Code Online (Sandbox Code Playgroud)