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
    Grep ping on a paragraph basis, then? – Jeff Schaller Dec 16 '16 at 20:09
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>
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.