Hao Shen
Hao Shen

Reputation: 2735

How to use Linux command(sed?) to delete specific lines in a file?

I have a file that contains a matrix. For example, I have:

1 a  2  b
2 b  5  b
3 d  4  b
4 b  7  b

I know it's easy to use sed command to delete specific lines with specific strings. But what if I only want to delete those lines where the second field's value is b (i.e., second line and fourth line)?

Upvotes: 0

Views: 1112

Answers (3)

sjr
sjr

Reputation: 9875

awk:

cat yourfile.txt | awk '{if($2!="b"){print;}}'

Upvotes: 1

Jude
Jude

Reputation: 13

Awk just work fine, just use code as below:

awk '{if ($2 != "b") print $0;}' file

if you want get more usage about awk, just man it!

Upvotes: 1

noalac
noalac

Reputation: 186

You can use regex in sed.

sed -i 's/^[0-9]\s+b.*//g' xxx_file

or

sed -i '/^[0-9]\s+b.*/d' xxx_file

The "-i" argument will modify the file's content directly, you can remove "-i" and output the result to other files as you want.

Upvotes: 4

Related Questions