How to remove tabs from blank lines using sed?
Asked Answered
B

6

17

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?

Burk answered 26/9, 2011 at 17:2 Comment(0)
C
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.

Clercq answered 26/9, 2011 at 17:9 Comment(1)
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.Mireyamiriam
A
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.

Arturoartus answered 26/9, 2011 at 17:17 Comment(0)
C
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.

Chicken answered 26/9, 2011 at 17:19 Comment(0)
A
1

What worked for me was:


sed -r '/^\s+$/d' my_file.txt > output.txt
Ash answered 7/12, 2021 at 15:2 Comment(0)
A
-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

Atomism answered 20/4, 2014 at 22:53 Comment(0)
A
-2
grep -o ".*" file > a; mv a file;
Axenic answered 28/12, 2013 at 12:23 Comment(1)
And this does what, exactly? Because it doesn't do what the OP asked.Zannini

© 2022 - 2024 — McMap. All rights reserved.