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

RegexMacosSed

Regex Problem Overview


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

Regex Solutions


Solution 1 - Regex

Try: Ctrl+V and then press Tab.

Solution 2 - Regex

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 - Regex

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 - Regex

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 - Regex

try awk

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

Solution 6 - Regex

A workaround for tab on osx is to use "\ ", an escape char followed by four spaces.

If you are trying to find the last instance of a pattern, say a " })};" and insert a file on a newline after that pattern, your sed command on osx would look like this:

sed -i '' -e $'/^\    \})};.*$/ r fileWithTextIWantToInsert' FileIWantToChange

The markup makes it unclear: the escape char must be followed by four spaces in order for sed to register a tab character on osx.

The same trick works if the pattern you want to find is preceded by two spaces, and I imagine it will work for finding a pattern preceded by any number of spaces as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZachView Question on Stackoverflow
Solution 1 - RegexyanView Answer on Stackoverflow
Solution 2 - RegexwisbuckyView Answer on Stackoverflow
Solution 3 - RegexgeekosaurView Answer on Stackoverflow
Solution 4 - RegexrobinstView Answer on Stackoverflow
Solution 5 - RegexkurumiView Answer on Stackoverflow
Solution 6 - Regexgao-shanView Answer on Stackoverflow