0

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)?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, thanks. But can you tell me which field in the command specify the b should be at second field? I didn't see any value like "2"...
The way the regex works is that the ^ marks the start of the line; the [0-9] looks for a single digit; the \s* looks for zero or more space-like characters (if the version of sed you're using supports it, which on Linux is normally the case — beware on non-Linux systems, though), followed by a b (and then the .* matches anything else on the line). The first command replaces all that with 'nothing', leaving you a blank line when there's a b in the second column; the second deletes the line (and really doesn't need the .* at the end of the regex). [...continued...]
[...continuation...] So, the regex matches the b in the second column (and doesn't match anything else in the sample data), but it isn't bullet proof. It would delete a line 9b c 7 x (because there can be zero spaces between the digit and the b. It also would delete 9 bad 8 y; it is not entirely clear whether your specification means that should be deleted or not. Fixing those issues is far from impossible; it is not clear whether it is necessary either.
Just change the \s* to \s+ would work, or simply a white space. But it depends on Hao's requirements and I believe he can finish it by himself :) @Jonathan Thank you for the explaining of reflex :)
Error spelling…I hate the small keyboard on the iPhone -_-
1

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!

Comments

1

awk:

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

2 Comments

I suspect $2 != "b" would print the correct lines; the == condition prints the lines that should be deleted. Also, you get a UUOC Award. You can and should use awk '...' yourfile.txt.
I love that page. cat "costs" me a process. How much did I pay for it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.