Shell script to remove spaces in file names

September 23rd, 2009 in Shell Scripting, Unix. Add comment
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

Ever ftp’d Windows files into a unix box and then found that some of your scripts break because the file names have spaces in them?

Here are couple of one liners that will help fix this by removing one or more spaces in the file names.

In bash shell:

#replace spaces with underscores in the file names
for file in *\ *; do mv “$file” “${file// /_}”; done
#remove all spaces in the file names
for file in *\ *; do mv “$file” “${file// /}”; done

The following will work in both k-shell and bash shell:

#replace spaces with underscores in the file names
for file in *\ *; do target=”$(echo $file | sed -e ’s/ /_/g’)”; mv “$file” “$target”;done;

#remove all spaces in the file names
for file in *\ *; do target=”$(echo $file | sed -e ’s/ //g’)”; mv “$file” “$target”;done;

Tags: ,

Leave a Reply

Sponsors