I have some text files which contain some columns separated by a various number of spaces, but instead I need one single tab as a separator. Is it possible to do in Bash?
18 Answers
To convert sequences of more than one space to a tab, but leave individual spaces alone:
sed 's/ \+ /\t/g' inputfile > outputfileTo do this for a number of files:
for inputfile in *
do sed 's/ \+ /\t/g' "$inputfile" > tmpfile && mv tmpfile "$inputfile"
doneor
for inputfile in *
do sed -i.bak 's/ \+ /\t/g' "$inputfile"
doneor
find . -type f -exec sed -i.bak 's/ \+ /\t/g' {} \; 4 If your character is multiple tabs you can also use tr -s:
-s, --squeeze-repeats replace each input sequence of a repeated character that is listed in SET1 with a single occurrenceFor example:
my_file.txt | tr -s " "All white spaces will become one.
1You 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 4 perl -p -i -e 's/\s+/\t/g' *.txt
The easiest answer using only bash is:
while read -r col1 col2 col3 ...; do echo -e "$col1\t$col2\t$col3..."
done <fileIf 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 <filee.g.
while read -r -a cols; do ( IFS=$'\t' echo "${cols[*]}" )
done <<EOF
a b c
d e f g h i
EOFproduces:
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 itr:
$ tr -s ' ' '\t' <<EOF
a b c
d e f g h i
EOF
a b c
d e f g h i 0 Try the following SED script:
sed 's/ */<TAB>/g' <spaces-file > tabs-fileWhere <TAB> is pressing the TAB key.
This is a very simple solution:
sed -E 's/\s+/\t/g' your_file > new_filesed basically works in this manner (sed 's/old_pattern/new_pattern/g').
In this case the old pattern is "\s+" which means find space "s" one or more time "+" and the back slash "\" to interpret that as regular expression.
The new pattern is tab "\t" which is written in regular expression format and the "g" is apply the replacement to all lines "globally".
The option -h, --tabs of col command can be useful (it's part of the util-linux package, col reads from standard input and writes to standard output).
cat file.txt | col -hor redirect the output to a file:
col -h <file.txt >output.txt