There are several reasons to replace spaces with underscore or another delimiter in files on linux. To begin with spaces may not be file system friendly i.e., accessing files on command line.
Let's explore a couple of ways to replace spaces in files in linux. Here are some commands using which we can achieve the same.
Using the Rename Command
Syntax of rename command
rename [options] 's/[filename element]/[replacement]/' [filename]
With this syntax, the command renames the file by replacing the first occurrence of the filename element with the replacement. In the command above:
- rename: Invokes the rename command.
- [options]: Provides an optional argument that changes the way the command executes.
- s: Indicates a substitute expression.
- [filename element]: Specifies the part of the filename you want to replace.
- [replacement]: Specifies a replacement for the part of the current filename.
- [filename]: Defines the file you want to rename.
n this example, every a character in the filename is replaced by an x, every b by a y, and every c by a z.
The rename command uses the following options:
- -a: Replaces all the occurrences of the filename element instead of just the first one.
- -f: Forces an overwrite of existing files.
- -h: Displays the help text.
- -i: Displays a prompt before overwriting existing files.
- -l: Replaces the last occurrence of the filename element instead of the first one.
- -n: Performs a dry run, making no permanent changes. Best combined with the verbose output (-v).
- -s: Renames the target instead of the symlink.
- -v: Shows a verbose version of the output.
- -V: Displays the command version.
Using the rename command to replace spaces with underscore
rename "s/ /_/g" *
Using the rename command to replace spaces with dash/hyphen
rename "s/ /-/g" *
Using for and mv replace space from file names
Using the for and mv command to replace spaces with underscore
for file in *; do mv "$file" $(echo $file | tr ' ' '_') ; done
Using the for and mv command to replace spaces with dash/hyphen
for file in *; do mv "$file" $(echo $file | tr ' ' '-') ; done
The above code provides ideal ways to replace space with underscore for files.