2

I have a list like the following:

Name_JR_1
1.1.1.1
Name_SR_1
2.2.2.2
Name_NONE_1
3.3.3.3

If I want to chose all associated name with following numerical syntax I can look for a pattern and print the matching line plus the after context or next line using the -A1 option, as follows:

grep "JR" -A1 file_name

and this will print what I want:

Name_JR_1
1.1.1.1

I need a way to invert this however, where I can REMOVE all entries which match the search pattern. However using the -v option with this syntax doesen't give me the results I want:

grep -v "JR" -A1 file_name

What I want the output to be like after this command is as follows:

Names_SR_1
2.2.2.2
Name_NONE_1
3.3.3.3.
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
JimRomeFan
  • 407
  • 6
  • 19

3 Answers3

5

Try:

$ awk '/JR/{getline;next} 1' file
Name_SR_1
2.2.2.2
Name_NONE_1
3.3.3.3

How it works

  1. /JR/{getline;next}

    This selects the lines containing JR. For those lines, this instructs awk to get the next line (getline) and then to skip the rest of the commands and start over on the following line (next).

  2. 1

    For any lines that don't have JR in them, this prints the line.

John1024
  • 109,961
  • 14
  • 137
  • 171
1

Another awk:

$ awk '/JR/||f==1{f=!f;next}1' file
Name_SR_1
2.2.2.2
Name_NONE_1
3.3.3.3

If we see JR or flag is up, reverse the flag and skip to next line.

James Brown
  • 36,089
  • 7
  • 43
  • 59
1

You can also use sed

$ sed '/JR/{N;d;}' ip.txt
Name_SR_1
2.2.2.2
Name_NONE_1
3.3.3.3
  • N will add next line to pattern space and then d will delete it
    • use N;N for two more lines, N;N;N for three more lines and so on


For a generic solution with awk

$ awk '/JR/{c=2} !(c && c--)' ip.txt
Name_SR_1
2.2.2.2
Name_NONE_1
3.3.3.3
Sundeep
  • 23,246
  • 2
  • 28
  • 103