How to set 4 space tab in bash

2019-03-12 15:13发布

问题:

It look like set tabstop=4 in VIM, but I don't know how to set it in bash

for example:

echo -e "1234567890\t321\n1\t2\n123\t1"

current output:

1234567890      321
1       2
123     1

I want output like this:

1234567890  321
1   2
123 1

It can be shown in anywhere, just like cat somefile or php -r 'echo "\t123";'

How can I set tab width in bash?

回答1:

That's not a property of your shell (or php or cat). It's your terminal that manages the output.

Use the tabs command to change the behavior:

$ tabs 4

$ echo -e "a\tb"      
a   b
$ tabs 12

$ echo -e "a\tb" 
a           b

(tabs is specified in POSIX, and output above is "faked": it's still a tab character between the two letters.)



回答2:

You can set either regular or irregular intervals using the tabs utility. It will work whether you're doing your own output, using cat to output a file that already includes tabs or using the output of a program you don't control.

However, if you're controlling your output it's preferable to use printf instead of echo and format strings instead of tabs.

$ printf '%-12s%8.4f %-8s%6.2f\n' 'Some text' 23.456 'abc def' 11.22
Some text    23.4560 abc def  11.22
$ format='%*s%*.*f %*s%*.*f\n'
$ printf "$format" -12 'Some text' 8 4 23.456 -8 'abc def' 6 2 11.22
Some text    23.4560 abc def  11.22

Unless you want someone else to be able to control the output of your program using the tabs utility.



回答3:

You can use setterm to set this

setterm -regtabs 4

I put it in my .bash_profile but its not bash related specifically



标签: bash space