Home > Software design >  How to delete first line of a file if it does not contain a specified string?
How to delete first line of a file if it does not contain a specified string?

Time:05-13

I have files that look like this:

username
Total 0
username
Total 0
username
Total 0
username
Total 0
username
Total 0

But some are malformed and have the incorrect first line like this:

Total 0
username
Total 0
username
Total 0
username
Total 0
username
Total 0

I need a one liner that will delete the first line if it does not contain username

i tried it with sed but it does not work:

sed -e '1!b' -e '/username/!d'

CodePudding user response:

perl -ne 'print if 1 != $. || /username/'

CodePudding user response:

$ awk 'NR>1 || /username/' file
username
Total 0
username
Total 0
username
Total 0
username
Total 0

CodePudding user response:

Easier to do this using awk:

awk 'NR == 1 && $0 != "username" {next} 1' file
  • Related