Sachin Jain
Sachin Jain

Reputation: 21842

Traverse files and replace all tabs to two spaces

I want to replace all tabs with 2 spaces in all files in my project directory. Here is the code I have written but it is not working as expected.

Tabs are as it is in the files.

for i in *
do
  sed 's/tab/spacespace/g' "${i}" > temp.txt && mv temp.txt "${i}"
done

Any suggestions ?

Upvotes: 1

Views: 253

Answers (2)

glenn jackman
glenn jackman

Reputation: 247022

You could also use expand

for f in *; do
    expand -t2 "$f" > tmp && mv tmp "$f"
done

expand is recommended option for below reason:

e.g. consider tabsize=8. (Larger tabsize chosen for ease of explanation.)

then <LINE_START>abc<TAB>pqrs should be represented as below:

T       T       T <~~~~~~ Tab markers on every 8th column, since tabsize=8.
abc     pqrs
-->     <-- This gap is 5 characters, not 8.

If someone blindly replaces all tabs by N spaces, then it will be wrong. That will however, work for replacing LEADING tabs.

expand utility smartly takes care of the situation mentioned above.

Upvotes: 2

Sachin Jain
Sachin Jain

Reputation: 21842

Found a silly mistake in my code. This is working

for i in * 
do
  sed 's/\t/  /g' "${i}" > temp.txt && mv temp.txt "${i}"
done

Upvotes: 0

Related Questions