How can I insert a tab character with sed on OS X?

48,739

Solution 1

Try: Ctrl+V and then press Tab.

Solution 2

Use ANSI-C style quoting: $'string'

sed $'s/foo/\t/'

So in your example, simply add a $:

echo -e "egg\t  \t\t salad" | sed -E $'s/[[:blank:]]+/\t/g'

Solution 3

OSX's sed only understands \t in the pattern, not in the replacement doesn't understand \t at all, since it's essentially the ancient 4.2BSD sed left over from 1982 or thenabouts. Use a literal tab (which in bash and vim is Ctrl+V, Tab), or install GNU coreutils to get a more reasonable sed.

Solution 4

Another option is to use $(printf '\t') to insert a tab, e.g.:

echo -e "egg\t  \t\t salad" | sed -E "s/[[:blank:]]+/$(printf '\t')/g"

Solution 5

try awk

echo -e "egg\t  \t\t salad" | awk '{gsub(/[[:blank:]]+/,"\t");print}'
Share:
48,739
Zach
Author by

Zach

Updated on July 05, 2022

Comments

  • Zach
    Zach almost 2 years

    I have tried:

    echo -e "egg\t  \t\t salad" | sed -E 's/[[:blank:]]+/\t/g'
    

    Which results in:

    eggtsalad
    

    And...

    echo -e "egg\t  \t\t salad" | sed -E 's/[[:blank:]]+/\\t/g'
    

    Which results in:

    egg\tsalad
    

    What I would like:

    egg salad