1

I am trying to convert all tabs to spaces using expand command.

Command: cat department.txt

Output :

1           QA 
2           DEV
3           OPS

On executing expand department.txt; the output is still same.

I have verified that my file contains tab characters by using od -c. Can someone explain why expand is not working ?

UPDATE: As muru pointed out in below comment; I was having wrong expectations from expand command, i was expecting tabs to be converted to single space; which caused the confusion. Expand command converts tab to equivalent spaces.

  • 1
    And have you verified that the output of expand has no tab characters? – muru Apr 8 '18 at 5:52
  • I am sorry. I was having wrong expectations. I was expecting tabs to be converted to be single space. On checking od -c on the output of expand i noticed tabs have been converted to equivalent spaces. Thanks – LoveWithMaths Apr 8 '18 at 5:59
1

To convert tabs to single spaces each, you can still use expand, with tabstops set to 1 instead of the default 8:

$ expand foo
1       QA
2       DEV
3       OPS
$ expand -t1 foo
1 QA
2 DEV
3 OPS

However, this still expands consecutive tabs to individual spaces:

$ vim foo
$ expand foo
1               QA
2               DEV
3               OPS
$ expand -t1 foo
1  QA
2  DEV
3  OPS

Depending on the behaviour you want, you can use that or tr:

$ tr -s '\t' ' ' < foo
1 QA
2 DEV
3 OPS
  • Since tr provides the feature of both squeezing and individual replace, why would one ever create a command like expand ? To me it just looks like a wrapper over tr without squeeze argument. Or am i missing something ? – LoveWithMaths Apr 8 '18 at 6:16
  • 1
    @linuxuser well, how would you replace a tab with n spaces (n depending on which column you're currently in) using tr? – muru Apr 8 '18 at 6:23
  • Was going through tr documentation. And below option is specified but i tried its not working [CHAR*REPEAT]. I tried tr '\t' '[ *5]' <file.txt. Do you know whats the use of this option ? – LoveWithMaths Apr 8 '18 at 6:49
  • 1
    @linuxuser try echo aeioubfgh | tr 'aeiou' '[c*3]d' and see if that makes sense to you. – muru Apr 8 '18 at 7:15
  • Yes makes sense. so to answer your above question. yes it cannot be achieved via tr. for which one can use expand/unexpand command always. – LoveWithMaths Apr 8 '18 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.