如何匹配文件中的一些单词并列出该匹配单词的所有行?(没有正则表达式)

显示ore在以地点名称结尾的地点工作的所有员工的详细信息

EmpID:Name:Designation:UnitName:Location:DateofJoining:Salary
1001:Thomson:SE:IVS:Mumbai:10-Feb-1999:60000
1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1003:Jackson:DM:IMS:Hyderabad:23-Apr-1985:90000
1004:BobGL::ETA:Mumbai:05-Jan-2004:55000
1005:Alice:PA:::26-Aug-2014:25000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000
1007:Kirsten:PM:IMS:Mumbai:26-Aug-2014:45000
1004:BobGL::ETA:Mumbai:05-Jan-2021:55000

预期输出:

1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000
1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000

这是我试过的代码,它只显示位置,但我想要完整的细节

cut -d ":" -f4 employee.txt | grep 'ore>' 

编辑:已解决

grep "`cut -d ":" -f5 employee.txt | grep 'ore>'`$" employee.txt

得到输出:

谢谢大家的帮助:)

回答

这里一个非正则表达式的方法使用awk

awk -F: -v s="ore" '(n=index($5,s)) && (n + length(s)-1) == length($5)' file

1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000

细节:

  • index($5,s)函数ore$5每行的第五列中查找输入字符串的位置
  • (index($5,s) + length(s)-1) == length($5)检查是为了确保ore$5

正则表达式方法会更简单:

awk -F: -v s="ore" '$5 ~ s "$"' file

  • @Babbaranish don't use grep for anything involving matching on fields, awk is simpler, more robust and more easily extensible. If your string was, say `.txt` instead of `ore` you could use the awk solution as-is but you couldn't just use the same `grep` solution as you did for `ore` because now you have a regexp metachar (`.`) to have to add code to handle in the search string. Similarly if your input only had 5 fields instead of 7 you could again just use the awk solution as-is but you'd have to change any currently posted grep solution because your target string no longer has `:` after it.

回答

我们可以awk在这里使用这个简单的解决方案。根据 OP 的要求,没有正则表达式方法。简单的解释是:检查第 5 个字段的最后 3 个字符是否为 ore 然后打印该行。

awk 'BEGIN{FS=OFS=":"} substr($5,length($5)-2)=="ore"' Input_file

通用答案:根据 Ed 先生的好建议,在此处添加更通用的解决方案。可以根据字符串设置尾部值的位置需要查看。

awk 'BEGIN{FS=OFS=":"; tail="ore"} substr($5,length($5)-length(tail)+1)==tail' Input_file


以上是如何匹配文件中的一些单词并列出该匹配单词的所有行?(没有正则表达式)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>