开发者

How to remove tabs from blank lines using sed?

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?


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.


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.


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.


What worked for me was:


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


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


grep -o ".*" file > a; mv a file;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜