36

In an interactive bash terminal how do I enter a tab character? For example, if I wanted to use sed to replace "_" with tabs I'd like to use:

echo $string | sed 's/[_]/TAB/g' 

Where TAB means the tab key. This works in a shell script not interactively where when I hit the tab key I get no character and a clank noise sounds. I've also tried \t but it only places t's in the string and not tabs.

Note this is mac osx.

2 Answers 2

70

Precede it with Control + V, followed by Tab to suppress the usual expansion behavior.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting strange results. Entering Control + V one time does nothing. Doing it a 2nd times gives me a ^V where I wanted a tab and replaces the "_" chars with nothing.
@grok12: "Precede", not "replace". [Control] + [V], followed by [Tab].
works on Linux too. I guess it's more to do with bash than the OS.
3

Since this question is tagged "bash"... using the "ANSI-C quoting" feature of the Bash shell is probably preferable. It expands ANSI C-style escape sequences such as \t and \n and returns the result as a single-quoted string.

echo $string | sed $'s/_/\t/g' 

This does not rely on your terminal understanding the Control+V (insert next character literally) key binding—some may not. Also, because all the "invisible" characters can be represented literally, your solution can be copy-pasted without loss of information, and will be much more obvious/durable if you're using including this sed invocation in a script that other people might end up reading.

Also note that macOS's version of sed is the BSD version. GNU sed will interpret character escapes like \t in the replacement pattern just fine, and you wouldn't even need above workaround.

You can install GNU sed with MacPorts, and it should be made available as gsed, but Homebrew might supersede your system's sed depending on how you have your $PATH variable arranged.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.