6

I've got a file with QR-code lines and I want to grep for only those whose subsequences do not increase in length. Example:

This one is good because the next sequence is less or same as previous:

####### ###### ### ### ## # # #

This one is wrong:

### ## ## ### ### ### ###### ##

I started off like this:

egrep "[^#](####)+[ ]+(##)+" qr.txt

but then I realised it's going to be impossible to continue..

1
  • I updated your question to help clarify the requirement - do you mean that each chunk of #'s should have no more than (same as, or fewer) #'s than the previous chunk?
    – Jeff Schaller
    Commented Dec 22, 2015 at 16:59

2 Answers 2

11
grep -vE '(^| )(#+) .*\2#' <<END
####### ###### ### ### ## # # #
### ## ## ### ### ### ###### ##
END
####### ###### ### ### ## # # #
5
  • Nice, but I think he wants the opposite, so grep -v ....
    – jimmij
    Commented Dec 22, 2015 at 17:03
  • yes. i think so too. i think maybe (since it is clearer now) you can drop the # after \2 - if \2 is found again at all the sequence doesn't decrease. \2# only finds the increase.
    – mikeserv
    Commented Dec 22, 2015 at 17:05
  • Very neat solution +1, but I think you should invert the match with -v.
    – chaos
    Commented Dec 22, 2015 at 17:07
  • 1
    @mikeserv, the requirements clearly state "the next sequence is less or same as previous" is "good" -- \2# is required Commented Dec 22, 2015 at 17:10
  • that's a good point - i contest its clarity considering the previous paragraph requires sequences which decrease in length. either way, it is a good answer.
    – mikeserv
    Commented Dec 22, 2015 at 17:21
3

With awk:

awk '{l=length($1);for(i=2;i<=NF;i++){if(length($i)>l){next};l=length($i)}}1' file
  • l=length($1) sets the varibale l to the length of the first field.
  • for(i=2;i<=NF;i++) loops trough all fields starting at the second.
  • if(length($i)>l if the length of that field is greater than the length of the last field:
    • next; skip to the next line.
  • l=length($i) set the l variable for the next iteration.

You must log in to answer this question.

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