How can I replace all of the spaces at the beginning of each line with a tab?

I would prefer to use sed for this.

  • 2
    @StephenRauch Did you mean to have a ^ in there? – Fox Apr 23 '17 at 20:15
  • @steeldriver That worked perfectly, thank you so much for your help! – user455555009 Apr 23 '17 at 20:18
  • Are you certain that you wanted to replace all the 0x20 with a 0x09, indiscriminately? Wouldn't you rather convert groups of the spaces so as to preserve levels of indentation? – can-ned_food Apr 23 '17 at 21:53


TAB=$(printf '\t')
sed "s/^  */$TAB/" < file.in > file.out

Some shells (ksh93, zsh, bash, mksh and FreeBSD sh at least) also support a special form of quotes ($'...') where things like \t are expanded.

sed $'s/^  */\t/' < file.in > file.out

The fish shell expands those outside of quotes:

sed 's/^  */'\t/ < file.in > file.out

Some sed implementations like GNU sed also recognise \t as meaning TAB by themselves. So with those, this would also work:

sed 's/^  */\t/' < file.in > file.out

Portably, awk does expand \t inside its double quotes. And also uses extended regular expressions, so one can use x+ in place of xx*:

awk '{sub(/^ +/, "\t"); print}' < file.in > file.out

If you're using GNU/Linux, there's sed -r to enable extended regular expressions:

 echo "        lots of spaces    " | sed -r 's:^\s+:\t:'

where only the leading spaces are all replaced with a single tab.

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.