views:

699

answers:

4

How do I replace whitespaces with tabs in linux in a given text file?

+1  A: 

I think you can try with awk

awk -v OFS="\t" '$1=$1' file1

or SED if you preffer

sed 's/[:blank:]+/,/g' thefile.txt > the_modified_copy.txt

or even tr

tr -s '\t' < thefile.txt | tr '\t' ' ' > the_modified_copy.txt

or a simplified version of the tr solution sugested by Sam Bisbee

tr ' ' \\t < someFile > someFile
Jonathan
In your sed example, best practices dictate that you use tr to replace single characters over sed for efficiency/speed reasons. Also, tr example is much easier this way: `tr ' ' \\t < someFile > someFile`
Sam Bisbee
Of course, tr has better performance than sed, but the main reason I have for loving Unix is that there're many ways to do something. If you plan to do this substitution many times you will search a solution with a good performance, but if you are going to do it only once, you will serach for a solution wich involves a command that make you feel confortable.
Jonathan
A: 

perl -p -i -e 's/ /\t/g' file.txt

John Millikin
A: 
perl -i -p -e 's/\s+/\t/g' file
ire_and_curses
+9  A: 

Use the unexpand(1) program


UNEXPAND(1)                      User Commands                     UNEXPAND(1)

NAME
       unexpand - convert spaces to tabs

SYNOPSIS
       unexpand [OPTION]... [FILE]...

DESCRIPTION
       Convert  blanks in each FILE to tabs, writing to standard output.  With
       no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are  mandatory  for  short  options
       too.

       -a, --all
              convert all blanks, instead of just initial blanks

       --first-only
              convert only leading sequences of blanks (overrides -a)

       -t, --tabs=N
              have tabs N characters apart instead of 8 (enables -a)

       -t, --tabs=LIST
              use comma separated LIST of tab positions (enables -a)

       --help display this help and exit

       --version
              output version information and exit

. . .
. . .
DigitalRoss
I'd never seen this before... love it.
fiXedd