Replace Whitespaces with Tabs in Linux

Replace tab with variable amount of spaces, maintaining the alignment

The POSIX utility pr called as pr -e -t does exactly what you want and AFAIK is present in every Unix installation.

$ cat file
ABC 1437 1 0 71 15.7 174.4
DEF 0 0 0 1 45.9 45.9
GHIJ 2 3 0 9 1.1 1.6

$ pr -e -t file
ABC 1437 1 0 71 15.7 174.4
DEF 0 0 0 1 45.9 45.9
GHIJ 2 3 0 9 1.1 1.6

and with the tabs visible as ^Is:

$ cat -ET file
ABC^I1437^I1^I0^I71^I15.7^I174.4$
DEF^I0^I0^I0^I1^I45.9^I45.9$
GHIJ^I2^I3^I0^I9^I1.1^I1.6$

$ pr -e -t file | cat -ET
ABC 1437 1 0 71 15.7 174.4$
DEF 0 0 0 1 45.9 45.9$
GHIJ 2 3 0 9 1.1 1.6$

How can I convert tabs to spaces in every file of a directory?

Warning: This will break your repo.

This will corrupt binary files, including those under svn, .git! Read the comments before using!

find . -iname '*.java' -type f -exec sed -i.orig 's/\t/ /g' {} +

The original file is saved as [filename].orig.

Replace '*.java' with the file ending of the file type you are looking for. This way you can prevent accidental corruption of binary files.

Downsides:

  • Will replace tabs everywhere in a file.
  • Will take a long time if you happen to have a 5GB SQL dump in this directory.

Using sed to replace tab with spaces

In sed replacement is not supposed to be a regex, so use:

sed -i.bak $'s/\t/    /g' filename

On gnu-sed even this will work:

sed -i.bak 's/\t/    /g' filename

How can I convert spaces to tabs in Vim or Linux?

Using Vim to expand all leading spaces (wider than 'tabstop'), you were right to use retab but first ensure 'expandtab' is reset (:verbose set ts? et? is your friend). retab takes a range, so I usually specify % to mean "the whole file".

:set tabstop=2      " To match the sample file
:set noexpandtab " Use tabs, not spaces
:%retab! " Retabulate the whole file

Before doing anything like this (particularly with Python files!), I usually set 'list', so that I can see the whitespace and change.

I have the following mapping in my .vimrc for this:

nnoremap    <F2> :<C-U>setlocal lcs=tab:>-,trail:-,eol:$ list! list? <CR>

Replacing tab with spaces to maintain n-space alignment

Since you have spaces before tabs you can use this sed:

sed $'s/ *\t/    /g' test
A B
A B
A B
A B

This will also replace 0 or more spaces before tab by 4 spaces.



Related Topics



Leave a reply



Submit