The sed command can use a full stop to find a wild card symbol, and so .* retrieves everything on the line.

Is it possible to say that I wish any symbol at all except (in this case) spaces? So:

FredSmith - would be valid

Fred&Ginger - would be valid

6times7 - would be valid

One too many - would not be valid


Yes, it's possible.

echo "One too many" | sed -n '/^[^[:space:]]*$/p'

The above command returns nothing

echo "FredSmith" | sed -n '/^[^[:space:]]*$/p'

While the latter prints FredSmith

  • [:space:] - POSIX character class for space characters

  • /^[^[:space:]]*$/p - means "print match if it contains only non-space characters [^[:space:]]" (used negated character class)

  • Ideal - thank you! Out if curiosity can you check against other characters, so a string that has no 'Z's in it for example? – HugMyster Jun 8 '17 at 11:11
  • @HugMyster, welcome. Yes, to match the string containing any character(including space) except Z character - use pattern /^[^Z]*$/ – RomanPerekhrest Jun 8 '17 at 11:14

Use negated character classes ([^ ] or [^[:space:]]) as Roman showed, or invert the match as below. Which one is better depends on the surrounding structure.

$ cat foo.txt
with space
$ sed '/ /d'  < foo.txt     # (d)elete the line on match
$ sed -n '/ /!p' < foo.txt  # (p)rint if the pattern does not (!) match

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.