user3304726
user3304726

Reputation: 259

Deleting lines matching a string in a file

I have multiple lines in a file. some lines start in the pattern below

0 8234 <Enter_newLine>
0 12 <Enter_newLine>
1 2  <Enter_newLine>

I wanted to delete the lines which start with 0 as shown above. Can someone please help me in this

Upvotes: 1

Views: 45

Answers (4)

Jotne
Jotne

Reputation: 41454

This awk should do:

awk '$1!="0"' file
1 2  <Enter_newLine>

This removes line where first field is just 0.

Upvotes: 0

gniourf_gniourf
gniourf_gniourf

Reputation: 46833

If you want to edit the file, you can use ed, the standard editor:

ed -s file < <(printf '%s\n' g/^0/d w q)

This uses the g/re/d construct: g to use the whole file, /re/ is the regex to work with, here ^0 to match lines starting with 0 and d to delete those lines. We then send the commands w (write) and q (quit).

The same without bashisms:

printf '%s\n' g/^0/d w q | ed -s file

Upvotes: 3

heemayl
heemayl

Reputation: 42047

You can also try sed:

sed -i '/^0[[:blank:]]\+/d' file.txt

Assuming that there can be one or more space or tab after initial 0, no other character.

Upvotes: 2

Tom Fenech
Tom Fenech

Reputation: 74655

This is very simple to do in awk:

awk '!/^0/' file

Any line starting with a 0 will not be printed.

To overwrite the input file, you can use the standard trick:

awk '!/^0/' file > tmp && mv tmp file

You could also use grep:

grep -v '^0' file

The -v switch means that only lines that don't match the pattern are printed.

Upvotes: 4

Related Questions