Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I've some text files which contain some colums seperated by a various number of spaces, but instead I need one single tab as a seperator. Is it possible to do in Bash?

share|improve this question
    
Thanks for the great input, but i have some single spaces inside a column, so i have to avoid tabbing a single space. sorry for that ,isinformation. –  user_unknown Feb 2 '11 at 22:49

5 Answers 5

up vote 15 down vote accepted

To convert sequences of more than one space to a tab, but leave individual spaces alone:

sed 's/ \+ /\t/g' inputfile > outputfile

To do this for a number of files:

for inputfile in *
do
    sed 's/ \+ /\t/g' "$inputfile" > tmpfile && mv tmpfile "$inputfile"
done

or

for inputfile in *
do
    sed -i .bak 's/ \+ /\t/g' "$inputfile"
done

or

find . -type f -exec sed -i .bak 's/ \+ /\t/g' {} \;
share|improve this answer

The easiest answer using only bash is:

while read -r col1 col2 col3 ...; do
    echo -e "$col1\t$col2\t$col3..."
done <file

If there are a variable number of columns, you can do this, but it will only work in bash, not sh:

while read -r -a cols; do
    (
        IFS=$'\t'
        echo "${cols[*]}"
    )
done <file

e.g.

while read -r -a cols; do
    (
        IFS=$'\t'
        echo "${cols[*]}"
    )
done <<EOF
a b   c
d   e    f
  g h i
EOF

produces:

a   b   c
d   e   f
g   h   i

(there is a tab in between each, but it's hard to see when I paste it here)

You could also do it using sed or tr, but notice that the handling of blanks at the start produces different results.

sed:

$ sed 's/  */\t/g' << EOF
a b   c
d   e    f
  g h i
EOF
a       b       c
d       e       f
        g       h       i

tr:

$ tr -s ' ' '\t' <<EOF
a b   c
d   e    f
  g h i
EOF
a       b       c
d       e       f
        g       h       i
share|improve this answer
    
Thank you very much! –  user_unknown Feb 2 '11 at 22:52

You can use sed to replace a number of spaces with a tab.:

Example to replace one-or-more-spaces with one tab:

cat spaced-file | sed 's/ \+/\t/g' > tabbed-file
share|improve this answer
    
The OP said the number of spaces was variable, so I don't think this solution will work. –  Mikel Feb 2 '11 at 22:35
    
@Mikel. Oops. Thanks for pointing that out. I've edit the post to allow matching for variable spaces. –  IvanGoneKrazy Feb 2 '11 at 22:45
    
this worked for me , thanks –  emdog4 Sep 10 '12 at 13:30

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

share|improve this answer

Try the following SED script:

 sed 's/  */<TAB>/g' <spaces-file > tabs-file

Where <TAB> is pressing the TAB key.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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