Barnesy
Barnesy

Reputation: 273

Removing line that contains more than one word

I need to remove a line in a specified file if it has more than one word in it using a bash script in linux.

e.g. file:

$ cat testfile

This is a text
file

This line should be deleted
this-should-not.

Upvotes: 2

Views: 1974

Answers (7)

Tom Lime
Tom Lime

Reputation: 1

This should satisfy your needs:

cat filename | sed -n '/^\S*$/p'

Upvotes: 0

talo
talo

Reputation: 1

If you want to edit files in-place (without any backups), you may also use man ed:

cat <<-'EOF' | ed -s testfile
H
,g/^[[:space:]]*/s///
,g/[[:space:]]*$/s///
,g/[[:space:]]/.d
wq
EOF

Upvotes: 0

lhf
lhf

Reputation: 72312

awk 'NF<=1{print}' testfile

a word being a run of non-whitespace.

Upvotes: 3

Tom Shaw
Tom Shaw

Reputation: 660

Easy enough:

$ egrep -v '\S\s+\S' testfile

Upvotes: 1

Tom Shaw
Tom Shaw

Reputation: 660

Just for fun, here's a pure bash version which doesn't call any other executable (since you asked for it in bash):

$ while read a b; do if [ -z "$b" ]; then echo $a;fi;done <testfile

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

$ sed '/ /d' << EOF
> This is a text
> file
> 
> This line should be deleted
> this-should-not.
> EOF
file

this-should-not.

Upvotes: 0

Mat
Mat

Reputation: 206689

awk '!/[ \t]/{print $1}' testfile

This reads "print the first element of lines that don't contain a space or a tab". Empty lines will be output (since they don't contain more than one word).

Upvotes: 1

Related Questions