'How to delete first line of a file if it does not contain a specified string?
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'
Solution 1:[1]
perl -ne 'print if 1 != $. || /username/'
Solution 2:[2]
$ awk 'NR>1 || /username/' file
username
Total 0
username
Total 0
username
Total 0
username
Total 0
Solution 3:[3]
Easier to do this using awk:
awk 'NR == 1 && $0 != "username" {next} 1' file
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | choroba |
| Solution 2 | Ed Morton |
| Solution 3 | anubhava |
