Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace spaces with underscores via BASH

Suppose i have a string, $str. I want $str to be edited such that all the spaces in it are replaced by underscores.

Example

a="hello world" 

I want the final output of

echo "$a" 

to be hello_world

like image 257
Ayush Mishra Avatar asked Oct 29 '13 14:10

Ayush Mishra


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you change underscore space in Unix?

The ${name/pattern/replace} replaces pattern to replace (Bash Parameter Expansion). If pattern starts with / (here pattern is / + Space ), it replaces all the occurencies. Then mv renames file from name to new name with replaced spaces.

How do you replace all spaces in a string in Bash?

Replace All Spaces With Bash. Bash shell supports a find and replace via substitution for string manipulation operation. The syntax is as follows: Replace all matches of Pattern with Replacement.

How do I replace spaces with underscores in Ubuntu terminal?

Open your Ubuntu command line, the Terminal, either through the Application Launcher search or the Ctrl+Alt+T shortcut. Here is the syntax of the command you will be using: I ran the same command to replace spaces with underscores in my Downloads folder:

How to use find and Replace command in Bash shell?

Bash shell supports a find and replace via substitution for string manipulation operation. The syntax is as follows: $ {varName//Pattern/Replacement} Replace all matches of Pattern with Replacement. x = " This is a test " echo "$ {x// /}" ### replace all spaces with * #### echo "$ {x// /*}" Sample outputs:

How do I copy and paste a bash script?

Tip: Instead of typing the whole script into you bash file, you can copy it from here and paste in the Terminal by using the Ctrl+Shift+V, or by using the Paste option from the right-click menu. This is how your file will look like:


1 Answers

You could try the following:

str="${str// /_}" 
like image 196
William Hay Avatar answered Sep 18 '22 13:09

William Hay