Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace intraline tabs with spaces, maintaining alignment?

Tags:

regex

vim

sed

I like to use spaces for indentation rather than tabs; replacing tabs at the beginning of a line is easy in sed or vim:

s/^I/    /g

But if there are tabs within a line (pretend the spaces are the width of the tab char):

'foo'^I ^I  => 'bar',
'bazzle'^I  => 'qux',

Each tab doesn't correspond to a set number of spaces to maintain the alignment. Anyone have a sly idea of how to replaces those tab characters with spaces while keeping the correct alignment?

like image 254
Drew Stephens Avatar asked Oct 06 '09 19:10

Drew Stephens


2 Answers

Under Linux and BSD, look up the expand and unexpand command line tools. expand will convert tabs to spaces, and unexpand performs the opposite operation. The simplest usage is:

expand filename

If you are like me, using 4 spaces for tabs, then:

expand -t 4 filename

By default, expand prints to the standard output and leave the original file in tact. To make in-place replacements, you have at least two choices:

$ cp filename backup
$ expand -t 4 filename > tempfile
$ mv tempfile filename

Or, you can invoke expand within vi:

$ vi filename
:%!expand -t 4
like image 196
Hai Vu Avatar answered Sep 28 '22 08:09

Hai Vu


In Vim:

:retab

or, if you have tabs after spaces:

:retab!
like image 42
cmcginty Avatar answered Sep 28 '22 07:09

cmcginty