Placing every character on a new line

Use grep, in example:

$ grep -o . file
$ echo This is a sentence. | grep -o .

or fold:

$ fold -w1 file
$ echo This is a sentence. | fold -w1

Using sed replace every character with itself followed by a newline:

sed 's/./\0\n/g' -i filename

  • sed $'s/./&\\\n/g' (with BSD sed)
    • Or sed 's/./&\n/g' with GNU sed
    • Doesn't include empty lines for linefeeds
  • fold -w1
    • -w specifies width in characters
    • Doesn't include empty lines for linefeeds
  • while IFS= read -r -n1 -d '' c; do printf %s\\n "$c"; done
    • Includes empty lines for linefeeds with -d ''
    • The only option for read specified by POSIX is -r
  • gawk -F '' 'OFS="\n"{$1=$1}1'
    • Or awk 'BEGIN{FS="";OFS="\n"}{$1=$1}1' in nawk (BSD awk, the awk that comes with OS X); it doesn't work with multibyte characters though
    • Neither includes empty lines for linefeeds

All except the nawk command worked with non-ASCII characters in my environment when LC_CTYPE was set to a UTF-8 locale. None collapsed or stripped spaces.

Tags:

Bash