15

I'd like to use sed to remove tabs from otherwise blank lines. For example a line containing only \t\n should change to \n. What's the syntax for this?

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

6 Answers6

26

sed does not know about escape sequences like \t. So you will have to literally type a tab on your console:

sed 's/^    *$//g' <filename>

If you are on bash, then you can't type tab on the console. You will have to do ^V and then press tab. (Ctrl-V and then tab) to print a literal tab.

Hari Menon
  • 33,649
  • 14
  • 85
  • 108
  • 11
    If using bash, you could also do `sed $'s/^\t*$//g'`, because using a dollar-sign on a single-quoted string formats escape codes such as \t. – Max E. Sep 26 '11 at 17:14
1

The other posted solution will work when there is 1 (and only 1) tab in the line. Note that Raze2dust points out that sed requires you to type a literal tab. An alternative is:

sed '/[^      ]/!s/   //g' file-name.txt

Which substitues away tabs from lines that only have tabs. The inverted class matches lines that contain anything bug a tab - the following '!' causes it to not match those lines - meaning only lines that have only tabs. The substitution then only runs on those lines, removing all tabs.

Kyle Burton
  • 26,788
  • 9
  • 50
  • 60
1

To replace arbitrary whitespace lines with an empty line, use

sed -r 's/^\s+$//'

The -r flag says to use extended regular expressions, and the ^\s+$ pattern matches all lines with some whitespace but no other characters.

Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
0

What worked for me was:


sed -r '/^\s+$/d' my_file.txt > output.txt
-1

I've noticed \t is not recognized by UNIX. Being said, use the actual key. In the code below, TAB represents pressing the tab key.

$ sed 's/TAB//g' oldfile > newfile

Friendly tip: to ensure you have tabs in the file you are trying to remove tabs from use the following code to see if \t appears

$ od -c filename

-2
grep -o ".*" file > a; mv a file;
psxls
  • 6,807
  • 6
  • 30
  • 50