Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to insert tab in sed?

Tags:

What is the proper way to insert tab in sed? I'm inserting a header line into a stream using sed. I could probably do a replacement of some character afterward to put in tab using regular expression, but is there a better way to do it?

For example, let's say I have:

some_command | sed '1itextTABtext' 

I would like the first line to look like this (text is separated by a tab character):

text    text 

I have tried substituting TAB in the command above with "\t", "\x09", " " (tab itself). I have tried it with and without double quotes and I can't get sed to insert tab in between the text.

I am trying to do this in SLES 9.

like image 936
dabest1 Avatar asked Dec 05 '11 23:12

dabest1


People also ask

How do I add a tab in Linux?

Use Ctrl+V (or Control+V on a Mac) and then the tab key. That will put a literal tab on the command line, which can be useful if (like me) you need to grep for a single character in a field in a tab delimited text file.

How do I insert a tab in a text file?

The tab character can be inserted by holding the Alt and pressing 0 and 9 together.

How do you insert a tab at the beginning of each line in the list?

If you want to make sure that Word inserts a tab character, simply press Ctrl+Tab. This will work any time in Word but is of the most use at the beginning of lines.


2 Answers

Assuming bash (and maybe other shells will work too):

some_command | sed $'1itext\ttext' 

Bash will process escapes, such as \t, inside $' ' before passing it as an arg to sed.

like image 80
Aaron McDaid Avatar answered Sep 23 '22 14:09

Aaron McDaid


You can simply use the sed i command correctly:

some_command | sed '1i\ text    text2' 

where, as I hope it is obvious, there is a tab between 'text' and 'text2'. On MacOS X (10.7.2), and therefore probably on other BSD-based platforms, I was able to use:

some_command | sed '1i\ text\ttext2' 

and sed translated the \t into a tab.

If sed won't interpret \t and inserting tabs at the command line is a problem, create a shell script with an editor and run that script.

like image 38
Jonathan Leffler Avatar answered Sep 23 '22 14:09

Jonathan Leffler