I have a lot of files with tabs littered throughout, and I'd like to convert them all into spaces. I know about the expand command, but unfortunately I would have to type out every single file using it. Is there any easier way to do this on Linux?

link|improve this question

17% accept rate
feedback

2 Answers

There are lots of ways to do this. There are also lots of ways to shoot yourself in the foot while doing this if you're not careful or if you're new to Linux as you appear to be. Assuming that you can create a list of files that you want to convert, either by using something like find or manually with an editor, just pipe that list into the following.

while read file
do
   expand "$file" > /tmp/expandtmp
   mv /tmp/expandtmp "$file"
done

One way you can shoot yourself in the foot with that is to make a typo so that you wind up mv'ing an empty file to all of the file names you specify, thereby deleting the contents of all your files. So be careful and test whatever you do first on a small set of files that you have backed up.

link|improve this answer
2  
Make the mv conditional on the success of expand: expand ... && mv ... – Dennis Williamson Jul 2 '10 at 10:04
feedback

Try the following:

find ./ -type f -exec sed -i ’s/\t/ /g’ {} \;

If you want four spaces, try:

find ./ -type f -exec sed -i ’s/\t/    /g’ {} \;
link|improve this answer
That will replace each tab by a single space. Since person mentioned using expand, I assume s/he wants the alignment of the text preserved. – garyjohn Jul 2 '10 at 5:27
You need to have 's/\t/ /g' to replace more than just one tab per line. – Daniel Andersson Mar 28 at 20:49
@DanielAndersson: Thanks, edited! – Nicolas Raoul Mar 29 at 5:00
A substantial speedup if there are many files is doing "find ./ -type f -exec sed -i ’s/\t/ /g’ {} +" (that is, "+" instead of "\;"), if the find version supports it (and I haven't personally met any version that doesn't, but it's not a POSIX standard, so I guess it could happen on some systems. See "-exec command {} +" in the manual). Instead of launching one instance of sed for every file, this will build an argument list with as many file name arguments as the system supports (getconf ARG_MAX=2097152 on my system), just like xargs, and thus launch much fewer sed processes. – Daniel Andersson Mar 29 at 6:43
feedback

Your Answer

 
or
required, but never shown

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