在每一行中查找特定单词并在unix shell脚本中显示结果

时间:2014-04-28 14:57:25

标签: bash shell unix

我想检查文件的每一行中是否存在任何单词rajrohit(忽略大小写)作为独立单词。如果发现匹配,则通过"找到" 如果没有那么" Not Found"在另一个文件中。因此每行必须有条目。

实施例

输入文件说(input.txt

raj ramu ram 
ram rohit sanjay sonu
savita ram raj rohit
raju ramu babita saurabhROHIT
raj sunita savita 
sachin sonu

输出文件(比如file.out

Found
Found
Found
Not Found
Found
Not Found

3 个答案:

答案 0 :(得分:2)

使用awk:

awk -v s1='(^| )raj( |$)' -v s2='(^| )rohit( |$)' '{
          print ($0~s1 || $0~s2)? "found": "not found"}' file
found
found
found
not found
found
not found

答案 1 :(得分:1)

#!awk -f
{
  print /\<(raj|rohit)\>/ ? "Found" : "Not Found"
}

答案 2 :(得分:1)

使用GNU awk支持\y(以及\< + \>)来匹配字词边界[1]

$ awk '!/\yraj\y/&&!/\yrohit\y/{printf "Not "} {print "Found"}' test.txt
Found
Found
Found
Not Found
Found
Not Found

$ awk '!/\<raj\>/&&!/\<rohit\>/{printf "Not "} {print "Found"}' test.txt
Found
Found
Found
Not Found
Found
Not Found

busybox awk似乎也支持\<\>(但不是\y):

$ busybox awk '!/\<raj\>/&&!/\<rohit\>/{printf "Not "} {print "Found"}' test.txt
Found
Found
Found
Not Found
Found
Not Found