Home > Blockchain >  Bash print all line except start to end pattern
Bash print all line except start to end pattern

Time:07-21

I have this input file with list of player names.

Cristiano Ronaldo
Anthony Martial
Jadon Sancho
Marcus Rashford
Bruno Fernandes
Fred
Scott McTominay
Donny Van De Beek
# Start U23 Team
Alvaro Fernandez
Zidane Iqbal
Facundo Pellistri
Hannibal Mejbri
Charlie Savage
# End U23 Team
Harry Maguire
Lisandro Martinez
Alex Telles

I want to exclude line starting with Start U23 Team and end with End U23 Team, so the end result will be:

Cristiano Ronaldo
Anthony Martial
Jadon Sancho
Marcus Rashford
Bruno Fernandes
Fred
Scott McTominay
Donny Van De Beek
Harry Maguire
Lisandro Martinez
Alex Telles

I can print the U23 Player with this command awk "/# End U23 Team/{f=0} f; /# Start U23 Team/{f=1}" file, but how to do vice versa ?

CodePudding user response:

Use the d command in sed to exclude lines.

sed '/# Start U23 Team/,/# End U23 Team/d' file

CodePudding user response:

awk "/# Start U23 Team/ {f=1} !f {print} /# End U23 Team/ {f=0}" file

CodePudding user response:

Using sed

$ sed -z 's/# Start.*# End U23 Team\n//' input_file
Cristiano Ronaldo
Anthony Martial
Jadon Sancho
Marcus Rashford
Bruno Fernandes
Fred
Scott McTominay
Donny Van De Beek
Harry Maguire
Lisandro Martinez
Alex Telles

CodePudding user response:

With GNU awk, please try following code, written and tested with shown samples only. Simply making use of RS variable where setting it to regex '(^|\n)# Start U23 Team\n.*\n# End U23 Team\n as per requirement and then in main program simply printing the lines.

awk -v RS='(^|\n)# Start U23 Team\n.*\n# End U23 Team\n' '{sub(/\n$/,"")} 1' Input_file

CodePudding user response:

awk '/# Start U23 Team/,/# End U23 Team/{next}1' file

CodePudding user response:

I can print the U23 Player with this command awk "/# End U23 Team/{f=0} f; /# Start U23 Team/{f=1}" file, but how to do vice versa ?

This code might be reworked following way

awk 'BEGIN{f=1} /# Start U23 Team/{f=0} f; /# End U23 Team/{f=1}' file

Explanation: BEGIN pattern allows executing action before starting processing lines, here I set f value to 1, /# Start U23 Team/ was swapped with /# End U23 Team/

  • Related