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.
03 Answers
With sed you can use this:
sed -i '/\w .*/d' fileor 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 (dat 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 (dat 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:
Print only the lines which don't have a second field:
awk -i inplace '!$2' filePrint only the lines for which the second field is empty:
awk -i inplace '$2 == ""' filePrint only the lines for which the number of fields (
NF) is smaller than 2 (equal to 1) (thanks steeldriver!):awk -i inplace 'NF<2' fileor
awk -i inplace 'NF==1' filePrint 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 fileIn 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\ ' filenameBasically 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.