0

I know how to remove all trailing spaces from a file, e.g :

sed -i 's/  *$//' file

Is there a way to do it, but not in lines containing only spaces?

Something in the spirit of :

sed -i 's/[a-zA-Z0-9;}{]  *$/[a-zA-Z0-9;}{]/' file
                         ^ keep the original characters

Preferably, but not necessariliy, with sed. Any linux supported solution will do.

Thanks

elad
  • 349
  • 2
  • 11

1 Answers1

2

Just make sure some other character appears before:

sed -r 's/([^\s])\s+$/\1/' file

This checks if a non-space character (\s) appears followed by any amount of spaces. If so, just print this non-space character back, so that the trailing spaces are removed.

Test

Using cat -vet to see the markers:

$ cat -vet a
hello    $
       $
bye   $
$ sed -r 's/([^\s])\s+$/\1/' a | cat -vet -
hello$
 $
bye$
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    If your sed supports `\s` for space then it probably also supports `\S` for non-space so you could use that instead of `[^\s]`. – Ed Morton Nov 26 '15 at 18:03