linux - grep while read 行替代

标签 linux bash shell

我有一个日志文件.log:

toto string1 tata string2 tito string3
tata tati string3
titi string1 tato string2 tati toto
.....
tutu string1 tita string2 tita string3

我需要从文件中的每一行提取 string1、string2 和 string3。 这些行可以包含一个或两个或三个字符串。

我第一次尝试使用 while read LINE do grep:

while read line; do 
z_string1=`echo $line | egrep 'string1' | cut -f2 xxx | cut -f1 xxxx`
z_string2=`echo $line | egrep 'string2' | cut -f2 xxx | cut -f1 xxxx`
z_string3=`echo $line | egrep 'string3' | cut -f2 xxx | cut -f1 xxxx`
echo "$z_string1,$z_string2,$z_string3" >> results.csv
done < file.log

这按预期工作,但根本没有优化,而且速度非常慢。

感谢您的帮助!

最佳答案

有多种方法可以实现这一目标。既然你似乎更喜欢 shell,你应该看看 awk ,它基本上就是为了做到这一点而设计的。

Perl 也正是用于此类任务。一个简单的脚本,其中包含一些正则表达式来匹配您的搜索词,然后是打印内容。

关于linux - grep while read 行替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16228585/

相关文章:

linux - BASH:如何选择字符串中给定字符之后的所有字符?

c - 在 C 程序中获取 shell 脚本的退出代码

shell - UNIX 将文件/目录重命名为大写

linux - Shell 编程 - 将特定单词替换为另一个单词

regex - SED 脚本 - 排除 self

php - 无法通过 Bash 脚本执行 PHP 脚本

bash - 如何在 bash 中启用默认文件完成

shell - 如何在 shell 中取消设置 vim 模式

linux - snmptranslate 在使用 snmp 和 snmpd 的 ubuntu 中不工作

linux - 如何将 PocketBeagle CAN 连接配置到车辆?