Reputation: 115
the input file looks like
Kick-off team 68 0
Ball safe 69 1
Attack 77 8
Attack 81 4
Throw-in 83 0
Ball possession 86 3
Goal kick 100 10
Ball possession 101 1
Ball safe 114 13
Throw-in 123 9
Ball safe 134 11
Ball safe 135 1
Ball safe 137 2
and at the end it should look like this:
Kick-off team 68 0
Attack 77 8
Attack 81 4
Ball possession 86 3
Goal kick 100 10
Ball safe 114 13
Throw-in 123 9
Ball safe 134 11
Ball safe 137 2
my solution is
awk '{print $NF}' test.txt | sed -re '2,${/(^0$|^1$)/d}'
how can i directly change the file, e.g. sed -i?
Upvotes: 0
Views: 67
Reputation: 67467
awk
to the rescue!
$ awk 'NR==1 || $NF && $NF!=1' file
or more cryptic
$ awk 'NR==1 || $NF*($NF-1)' file
Upvotes: 1
Reputation: 58371
This might work for you (GNU sed):
sed -i '1b;/\s[01]$/d' file
Other than the first line, delete any line ending in 0
or 1
.
Upvotes: 0
Reputation: 46826
Here's my take on this.
sed -i.bak -e '1p;/[^0-9][01]$/d' file.txt
The sed script prints the first line, then deletes all subsequent lines that match the pattern you described. This assumes that your first line would be a candidate for deletion; if it contains something other than 0 or 1 in the last field, this script will print it twice. And the -i
option is what tells sed to edit in-place (with a backup file).
Awk doesn't have an equivalent option for editing files in-place -- if you want that kind of functionality, you need to implement it in a shell wrapper around your awk script, as @sundeep suggested.
Note that I'm not using GNU sed, but this command should work equally well with it.
Upvotes: 1
Reputation: 23667
sed -i '2,$ {/[^0-9][01]$/d}' test.txt
2,$
lines to act upon, this one says 2nd line to end of file{/[^0-9][01]$/d}
from filtered lines, delete those ending with 0
or 1
'2,$ {/ [01]$/d}'
can be also used if character before last column is always a space
With awk
which is better suited for column manipulations:
awk 'NR==1 || ($NF!=1 && $NF!=0)' test.txt > tmp && mv tmp test.txt
NR==1
first line($NF!=1 && $NF!=0)
last column shouldn't be 0
or 1
$NF>1
if last column only have non-negative numbers> tmp && mv tmp test.txt
save output to temporary file and then move it back as original fileGNU awk
, there is inplace option awk -i inplace 'NR==1 || ($NF!=1 && $NF!=0)' test.txt
Upvotes: 2