Bash: How to Replace Space with Underscore (With Example)


You can use the following methods to replace spaces with underscores in Bash:

Method 1: Replace Space with Underscore in String

echo ${my_string// /_}

This particular example replaces all spaces with underscores in the string named my_string.

Method 2: Replace Space with Underscore in All Files in Folder

for name in *; do mv "$name" "${name// /_}"; done

This particular example replaces all spaces with underscores in all files in the current folder.

Note that the mv operator in Bash allows you to do a variety of tasks including renaming and moving files.

In this example, we use the mv operator to rename the files by replacing any spaces with underscores.

The following examples show how to use each of these methods in practice.

Example 1: Replace Space with Underscore in String

Suppose that we have the following string in Bash:

  • Hey there everyone welcome to the party

Suppose that we would like to replace each space in the string with an underscore instead.

We can use the following syntax to do so:

my_string="Hey there everyone welcome to the party"
echo ${my_string// /_} 

The following screenshot shows how to use this syntax in practice:

Bash replace space with underscore

Notice that each space in the string has been replaced with an underscore.

The resulting string is:

  • Hey_there_everyone_welcome_to_the_party

Note: If your string has several spaces in a row, each space will be replaced with its own underscore.

Example 2: Replace Space with Underscore in All Files in Folder

Suppose that we would like to replace all spaces with underscores in each file in the current folder.

To view the names of each file in the current folder, we can use the ls statement:

We can see that the current folder has the following files:

  • out 1.txt
  • out 2.txt
  • out 3.txt

We can use the following syntax to replace the spaces with underscores in each file name:

for name in *; do mv "$name" "${name// /_}"; done

The following screenshot shows how to use this syntax in practice:

bash replace space with underscore in all file names

Notice that the spaces in each file name have been replaced with underscores.

The files now have the following names:

  • out_1.txt
  • out_2.txt
  • out_3.txt

Note that any file names without spaces will simply be left unchanged.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Replace Text in String
Bash: How to Replace Specific Line in File
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply