0

I am writing a Bash script which should test if every line in input meet certain condition.

Is there a way to take the predicate and reduce all the line to either 0 or 1 so I don't have to code the looping code myself using a utility that is routinely standard or readily available in Linux distributions?

1
  • Please can you provide more information? e.g: example input and expected output data.
    – Attie
    Commented Apr 9, 2018 at 11:15

1 Answer 1

-1

Sample data (we want all lines that contain "want"):

$ cat x
not this
want this
not that
want that

You coud use awk:

  • Print a 1 if the line matches regex /want/
  • Print a 0 if the line does not match
$ cat x | awk '{if(match($0,/want/)){print 1}else{print 0}}'
0
1
0
1

Or try sed:

  • Replace lines that contain just 1 with 0 (otherwise they will pass through as a 1)
  • Replace lines containing "want" with a 1
  • Replace lines that are not a 1 with a 0
$ cat x | sed -re 's/^1$/0/' -e 's/^.*want.*$/1/' -e 's/^[^1][^$].*$/0/'
0
1
0
1
1
  • I'm going to ask for more information from OP... If you're not happy with a one liner, then I think the answer has to be "no" - it doesn't get much more simple that the awk example above...
    – Attie
    Commented Apr 9, 2018 at 11:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .