0

I have a file that looks something like this:

Volume1  
created=Monday  
blah blah  
foo foo  
lock mode=exclusive  
ops  
layer id=1  

Volume2  
created=Tuesday  
jibber jabber  
foo foo  
ops  
layer id=2  

Volume3  
created=Wednesday  
blaaah  
foooo  
lock mode=shared  
ops  
layer id=3

What I'd like to do is grep on "lock mode" and if that is there print that whole line, otherwise I'd like to print "NA". I can't seem to figure out how to print something for non-matching lines. I'm sure awk or sed could do this as well.

I've been trying code similar to:

grep -A6 Volume | grep "lock mode" <file>

I'd like the output to show the following, for this example:

lock mode=exclusive  
NA  
lock mode=shared
1
  • 1
    Grep ping on a paragraph basis, then?
    – Jeff Schaller
    Dec 16, 2016 at 20:09

3 Answers 3

3

It's easy with perl:

perl -l -00 -ne 'print /lock mode.*/ ? $& : "NA"'
  • -l sets the output field delimiter to newline
  • -00: paragraph mode (records are paragraphs)
  • -ne code: run code for every input record
  • if the record contains lock mode followed by any number of non-newline characters, then print what is matched ($&) or NA otherwise.

Basically the same as @iruvar's awk solution, but in perl.

3

With awk in paragraph mode

awk -v RS= '{match($0, /lock mode=[^\n]+/); 
  print RSTART? substr($0, RSTART, RLENGTH): "NA"}' file

The RS= causes each paragraph to be treated as a single record. The call to match populates the coordinates of lock mode=.... into predefined variables RSTART and RLENGTH. If RSTARTis non-zero, the substring corresponding to RSTART and RLENGTH is printed, otherwise NAis printed

0
2

With GNU sed

sed -n '
    /Volume/!d
    :a
    n
    /lock mode/{
        p
        d
        }
    /^\s*$/!ba
    c\NA
    ' <file>

With awk

awk '
    BEGIN{
        FS="\n"
        RS="\n\n"
    }
    /lock mode/{
        for(i=1;i<=NF;i++)
            if($i ~ /lock mode/)
                print $i
        next
    }
    {
        print "NA"
    }
    ' <file>
0

You must log in to answer this question.

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