1

I'd like to be able to print and see the trailing whitespaces in the text file (just display, not remove).

I've tried with cat -v which suppose to display non-printing characters, but it doesn't display them as expected (no visual difference between the lines). E.g.

$ printf "foo\nbar \t\n" > file.txt
$ cat -v file.txt 
foo
bar     

By print/display whitespaces I mean some visual human indication that the trailing whitespace is there in comparison to other lines without, either by some special character, color (like when files are displayed using git diff) or something similar.

Is there any other way?


Note: I'm on macOS Sierra, however I've got access to both GNU and BSD cat commands:

$ type -a cat
cat is /usr/local/opt/coreutils/libexec/gnubin/cat
cat is /bin/cat
$ cat --version
cat (GNU coreutils) 8.28
$ /bin/cat --version
/bin/cat: illegal option -- -
usage: cat [-benstuv] [file ...]
  • Thanks, seems to work fine, at least better than -v. -E doesn't exist for /bin/cat, but I've got GNU cat installed as well. – kenorb Nov 22 '17 at 13:08
  • cat -v does work, it just doesn’t do what you think it does — try cat -v /dev/urandom | head to see how it affects output. – Stephen Kitt Nov 22 '17 at 13:11
  • @kenorb -E does exist for /bin/cat , which version are you talking about – Sanket Nov 22 '17 at 13:12
  • cat -v prints non-printing characters fine, however whitespace is still a whitespace, so it's not really human visible in the terminal. – kenorb Nov 22 '17 at 13:12
  • @Sanket $ /bin/cat -E file.txt -> /bin/cat: illegal option -- E. – kenorb Nov 22 '17 at 13:13
3

gnu cat has the -E switch for that so with an input like

printf " one \ntwo \t\n"

it will print

 one $
two    $

There are many ways to emulate that behaviour e.g. use sed in "raw" mode:

sed -n l infile

or

paste -d '$' infile /dev/null

or use any text processing tool to add a $ before each newline...

You might also try something like

less -p '[[:blank:]]+$' infile

which will highlight the pattern (in this case the trailing blanks)...

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.