tags:

views:

114

answers:

5
sed "s/\(.*\)/\t\1/" $filename > $sedTmpFile && mv $sedTmpFile $filename

I am expecting this sed script to insert a tab in font of every line in $filename however it is not. For some reason it is inserting a t instead.. Strange..

+4  A: 

Not all versions of sed understand \t. Just insert a literal tab instead (press Ctrl-V then Tab).

Mark Byers
Ah yes; to clarify: not all versions of sed understand `\t` in the replacement part of the expression (it recognized `\t` in the pattern matching part just fine)
John Weldon
awwwwwwwwwwwwwwwwwww, ok that is pretty interesting. And strange. Why would you make it recognize it in one place but not the other...?
sixtyfootersdude
A: 

sed doesn't support \t, nor other escape sequences like \n for that matter. The only way I've found to do it was to actually insert the tab character in the script using sed.

That said, you may want to consider using Perl or Python. Here's a short Python script I wrote that I use for all stream regex'ing:

#!/usr/bin/env python
import sys
import re

def main(args):
  if len(args) < 2:
    print >> sys.stderr, 'Usage: <search-pattern> <replace-expr>'
    raise SystemExit

  p = re.compile(args[0], re.MULTILINE | re.DOTALL)
  s = sys.stdin.read()
  print p.sub(args[1], s),

if __name__ == '__main__':
  main(sys.argv[1:])
Roman Nurik
And the Perl version would be the shell one-liner "perl -pe 's/a/b/' filename" or "something | perl -pe 's/a/b/'"
tiftik
Nice, that's much better :-)
Roman Nurik
+2  A: 

You don't need to use sed to do a substitution when in actual fact, you just want to insert a tab in front of the line. Substitution for this case is an expensive operation as compared to just printing it out, especially when you are working with big files. Its easier to read too as its not regex.

eg using awk

awk '{print "\t"$0}' $filename > temp && mv temp $filename
ghostdog74
A: 

Using Bash you may insert a TAB character programmatically like so:

TAB=$'\t' 
echo 'line' | sed "s/.*/${TAB}&/g" 
echo 'line' | sed 's/.*/'"${TAB}"'&/g'   # use of Bash string concatenation
sedit
A: 

I'm using sed in Cygwin (bash) and escape characters work fine for me.

If I had to add a tab to the beginning of every line I would definitely use sed.

I would use ^ to match the beginning of the line instead of matching .* and doing the replace. It would have to be more efficient that way.

[~]
==> cat test.txt
line1
line2
line3
line4
line5

[~]
==> sed 's/^/\t/' test.txt
        line1
        line2
        line3
        line4
        line5

Please ignore my funky prompt. :-)

DevNull