使用 grep 命令在 shell 脚本的结果中进行换行

使用 grep 命令在 shell 脚本的结果中进行换行

我正在编写一个 shell 脚本来获取日志文件中的某些内容,然后使用命令grep打印所有结果。echo

我可以这样做,但假设日志包含多个搜索字符串实例,那么它会将所有结果打印在一行中。是否可以用换行符打印结果;如果我只是grep在 shell 中执行命令,那么它将用换行符打印,所以我想使用 shell 脚本也可以以相同的方式工作,但显然这不会发生。

我的 shell 脚本:

#!/bin/bash
messageStr='a senior leader of '$2
echo $messageStr
results=`grep "$messageStr" $1`
echo "results= " $results

我的日志文件:

A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women.

a senior leader of Aam Aadmi Party or AAP

A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women.

实际结果:

results=  A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women. a senior leader of Aam Aadmi Party or AAP

预期成绩:

results=  A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women. 
a senior leader of Aam Aadmi Party or AAP

如果需要任何其他信息,请告诉我。

答案1

未加引号的变量会进行分词(在 shell 参数扩展后,使用空格、制表符和换行符将扩展后的变量拆分为单独的参数)和通配符(扩展 shell 通配符)。通常,你应该总是双引号shell 变量除非你特别想要分词和/或通配符。有关更多信息,请参阅http://mywiki.wooledge.org/Quotes

如果我正确理解了你的问题,在这种情况下,你只需要引用参数$results

messageStr="a senior leader of $2"
echo "$messageStr"
results=$(grep "$messageStr" "$1")
echo "results=  $results"

顺便说一句,使用反引号进行命令替换(实际上)已被弃用;最好使用$()

附录http://shellcheck.net/在开发 shell 脚本时提供非常有用的反馈(例如,突出显示未引用的变量)。

相关内容