Bash: How to Replace Dash with Underscore


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

Method 1: Replace Dash with Underscore in String

echo ${my_string//-/_}

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

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

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

This particular example replaces all dashes 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 dashes with underscores.

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

Example 1: Replace Dash with Underscore in String

Suppose we have the following string in Bash:

  • This-is-a-great-day

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

We can use the following syntax to do so:

my_string="This-is-a-great-day"
echo ${my_string//-/_} 

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

Bash replace dash with underscore in string

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

The resulting string is:

  • This_is_a_great_day

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

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

Suppose that we would like to replace all dashes 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 dashes 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 dash with underscore in all file names in folder

Notice that the dashes 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 dashes will simply be left unchanged.

Related Tutorials

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

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