Home > Blockchain >  Searching for word and output 'none' if not found
Searching for word and output 'none' if not found

Time:06-27

I would like to search for word between 'start' and 'end' and output it and if not found, need to output 'none'

cat test.txt

start
item#1  item#2
item#4
end

start
item#1  item#3
item#4
end

start
item#1  item#2
item#5
end

I tried awk '/start/,/end/' | egrep -o item#3 || echo "none" test.txt

the output is as below

item#3

The wanted output is

none
item#3
none

Thanks.

CodePudding user response:

I believe this part is correct: awk '/start/,/end/', it shows the entries between "start" and "end".

Now what you want to do is:

  • Replace all non-#item3 by "none"

Wat you are doing is:

  • Only show the #item3 matches.

This is indeed not working.

Therefore, instead of a grep (a filtering mechanism), I'd opt for a sed "s/.../.../g" (a replacement mechanism).

CodePudding user response:

awk '
   /start/ {found=1; i=NR; a[i]="none"; next}
   /end/   {found=0;}
   found   {if($0 ~ "item#3"){a[i]="item#3"}}
   END{
      for(i in a) print a[i]
   }
' test.txt

none
item#3
none

Using variables

awk -v m1="start" -v m2="end" -v s="item#3" -v o="none" '
   $1==m1 {found=1; i=NR; a[i]=o; next}
   $1==m2 {found=0;}
   found  { $0 ~ s ? a[i]=s : ""}
   END{
      for(i in a) print a[i]
   }
' test.txt

none
item#3
none
  •  Tags:  
  • bash
  • Related