How do I remove lines with sed that contain more than 1 word?

I need to remove lines from a file that contain > 1 word. Here is an example of the file's content:

This line is not what I need printed-now. 

would print

This not printed-now. 

I have tried:

sed -n '/[a-zA-Z]* *[a-zA-Z]/p' 

This is a learning activity that has me stumped.

0

3 Answers

With sed you can use this:

sed -i '/\w .*/d' file 

or this, if the first word can contain anything but whitespace:

sed -i '/\S .*/d' file 
  • -i: modify the file in place.
  • /\w .*/d: if the pattern /\w .*/ (i.e. a word, a space and everything after that) is matched, delete (d at the end) the whole line.
  • /\S .*/d: if the pattern /\S .*/ (i.e. anything but whitespace, a space and everything after that) is matched, delete (d at the end) the whole line.

You have many options to do the same thing with awk. In all of the following cases, -i inplace is used to modify the file in place:

  1. Print only the lines which don't have a second field:

    awk -i inplace '!$2' file 
  2. Print only the lines for which the second field is empty:

    awk -i inplace '$2 == ""' file 
  3. Print only the lines for which the number of fields (NF) is smaller than 2 (equal to 1) (thanks steeldriver!):

    awk -i inplace 'NF<2' file 

    or

    awk -i inplace 'NF==1' file 
  4. Print only the lines for which the length of the second field is not zero:

    awk -i inplace '!length($2)' file 

Note that the -i inplace flag works only for awk versions greater than 4.1. For versions lower than this, the equivalent is to first save to an intermediate file and then rename this file as the initial one. For example, the first option would be like this:

awk '!$2' file > tmp && mv tmp file 

In all cases the output is this:

This not printed-now. 
4

I would use:

sed -E '/\S\s+\S/d' <Data.txt 

(ie, lines that contain something which is not a space, followed by any number of spaces, followed by something which is not a space).

One Item Per line This disappears This also disappears This-remains Leading-space Trailing-spaces 

becomes:

One Item This-remains Leading-space Trailing-spaces 

Use

sed -i '/what I need/c\ ' filename 

Basically it follows the approach-

sed -i '/pattern/c\ line_you_want_to_insert' filename 

Here line_you_want_to_insert will be blank as you want it removed.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like