bash grep newline

后端 未结 11 1749
渐次进展
渐次进展 2021-01-04 12:38

[Editorial insertion: Possible duplicate of the same poster\'s earlier question?]

Hi, I need to extract from the file:

first
second
         


        
相关标签:
11条回答
  • 2021-01-04 12:54

    grep -A1 "second" | grep -B1 "third" works nicely, and if you have multiple matches it will even get rid of the original -- match delimiter

    0 讨论(0)
  • 2021-01-04 12:55

    you could use

    $ grep -1 third filename
    

    this will print a string with match and one string before and after. Since "third" is in the last string you get last two strings.

    0 讨论(0)
  • 2021-01-04 12:56

    So you just don't want the line containing "first"? -v inverts the grep results.

    $ echo -e "first\nsecond\nthird\n" | grep -v first
    second
    third
    
    0 讨论(0)
  • 2021-01-04 13:03
    grep -v '^first' filename
    

    Where the -v flag inverts the match.

    0 讨论(0)
  • 2021-01-04 13:04

    Instead of grep, you can use pcregrep which supports multiline patterns

    pcregrep -M 'second\nthird' file
    

    -M allows the pattern to match more than one line.

    0 讨论(0)
  • 2021-01-04 13:06

    I don't really understand what do you want to match. I would not use grep, but one of the following:

    tail -2 file         # to get last two lines
    head -n +2 file      # to get all but first line
    sed -e '2,3p;d' file # to get lines from second to third
    

    (not sure how standard it is, it works in GNU tools for sure)

    0 讨论(0)
提交回复
热议问题