Unix [SOLVED]: grep lines that contain 1 character followed by another character

Unix [SOLVED]: grep lines that contain 1 character followed by another character

Home Forums Unix Unix [SOLVED]: grep lines that contain 1 character followed by another character

Tagged: , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #37028

    Anonymous

    QuestionQuestion

    I’m working on my assignment and I’ve been stuck on this question, and I’ve tried looking for a solution online and my textbook.

    The question is:

    List all the lines in the f3.txt file that contain words with a character b not followed by a character e.

    I’m aware you can do grep -i 'b' to find the lines that contain the letter b, but how can I make it so that it only shows the lines that contain b but not followed by the character e?

    #37029

    Anonymous

    Accepted AnswerAnswer

    You can go for the following two solutions:

    grep -ie 'b[^e]' input_file.txt
    

    or

    grep -ie 'b.' input_file.txt | grep -vi 'be'
    

    The first one does use regex:

    • 'b[^e]' means b followed by any symbol that is not e
    • -i is to ignore case, with this option lines containing B or b that are not directly followed by e or E will be accepted

    The second solution calls grep twice:

    • the first time you look for patterns that contains b only to select those lines
    • the resulting lines are filtered by the second grep using -v to reject lines containing be
    • both grep are ignoring the case by using -i
    • if b must absolutely be followed by another character then use b. (regex meaning b followed by any other char) otherwise if you want to also accept lines where b is not followed by any other character at all you can just use b in the first grep call instead of b..

      grep -ie 'b' input_file.txt | grep -vi 'be'
      

    input:

    BEBE
    bebe
    toto
    abc
    bobo
    

    result:

    abc
    bobo
    

    Source: https://stackoverflow.com/questions/48015371/grep-lines-that-contain-1-character-followed-by-another-character
    Author: Allan
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.