How to replace spaces in file or directory names with hyphens or underscores with the Linux shell.

Posted: February 24, 2013. At: 2:24 PM. This was 4 years ago. Post ID: 5409

This command will take all files and directories in a folder and replace all of the spaces in their names with hyphens. This could be a very useful command when you want the files to have sensible filenames.

john@adeptus-mechanicus ~ $ ls -hula | perl -e 'rename $_, s/\s+/-/gr for (<*>)'

This example will replace all of the spaces in the filenames with underscores.

john@adeptus-mechanicus ~ $ ls -hula | perl -e 'rename $_, s/\s+/_/gr for (<*>)'

Here is another method; using bash itself. Using this command: for f in *; do mv -iv “$f” “${f// /-}”; done;.

john@adeptus-mechanicus ~/Documents/mine $ ls -hula
total 8.0K
drwxrwxr-x  2 john john 4.0K Feb 24 14:10 .
drwxr-xr-x 10 john john 4.0K Feb 24 14:09 ..
-rw-rw-r--  1 john john    0 Feb 24 14:10 this is a file with spaces2.txt
-rw-rw-r--  1 john john    0 Feb 24 14:10 this is a file with spaces3.txt
-rw-rw-r--  1 john john    0 Feb 24 14:10 this is a file with spaces4.txt
-rw-rw-r--  1 john john    0 Feb 24 14:10 this is a file with spaces.txt
john@adeptus-mechanicus ~/Documents/mine $ for f in *; do mv -iv "$f" "${f// /-}"; done;
`this is a file with spaces2.txt' -&gt; `this-is-a-file-with-spaces2.txt'
`this is a file with spaces3.txt' -&gt; `this-is-a-file-with-spaces3.txt'
`this is a file with spaces4.txt' -&gt; `this-is-a-file-with-spaces4.txt'
`this is a file with spaces.txt' -&gt; `this-is-a-file-with-spaces.txt'
john@adeptus-mechanicus ~/Documents/mine $ ls -hula
total 8.0K
drwxrwxr-x  2 john john 4.0K Feb 24 14:10 .
drwxr-xr-x 10 john john 4.0K Feb 24 14:09 ..
-rw-rw-r--  1 john john    0 Feb 24 14:10 this-is-a-file-with-spaces2.txt
-rw-rw-r--  1 john john    0 Feb 24 14:10 this-is-a-file-with-spaces3.txt
-rw-rw-r--  1 john john    0 Feb 24 14:10 this-is-a-file-with-spaces4.txt
-rw-rw-r--  1 john john    0 Feb 24 14:10 this-is-a-file-with-spaces.txt
john@adeptus-mechanicus ~/Documents/mine $
1 responses to “How to replace spaces in file or directory names with hyphens or underscores with the Linux shell.

Leave a Reply