Bash Remove Spaces from String

Bash remove spaces from String

Using sed Command

Use the sed command to remove spaces from string without updating the original variable in Bash.

First, we stored the string value in the var variable. Then, we piped it to the sed command, a stream editor performing operations on the text streams. In the above case, we used it to replace whitespaces with nothing (i.e., removing whitespaces) in the given input string (var).

How are they removed? For that, we used sed-expression, which was 's/ //g'. Here, s denotes that it is a substitution operation. So the first / was the delimiter, which separated the given pattern to be matched and replaced.

In the above example, we matched spaces (whitespaces). As we did not want to replace the spaces with anything, no replacement was given after the second /. It means we wanted to replace the spaces with nothing that is removing spaces.

The g flag removed all spaces, not just the first one. If you want to remove the first space, omit the g flag. Finally, we used the echo statement to display the modified string on the Bash console. Note that the value in the var variable will not be modified.

Use the sed command to remove all spaces from the given string and update the original variable in Bash.

This example is similar to the previous one, but we used <<< (here-string) to redirect the string as standard input to the specified command. In the above example, the sed 's/ //g' <<< $var command combined the sed command with << You can also store the output, returned by $(…) syntax, in a new variable rather than updating the value of the var variable.

Use the sed command to remove all spaces from the multiline string. The output value must be a single-line string containing no space characters.

The above code is similar to the last example excluding two things. First, we initialized the var variable with a multiline string value, and second, we used ':a;N;$!ba;s/\n/ /g;s/ //g' as sed-expression.

In the sed-expression, the :a;N;$!ba; construct was used to join multiple lines into a single line. It read all the lines into a pattern space and replaced the newline character (\n) with a space. How? Let's break it down further:

  • The :a was a label declaration command that we used to define a labelled called "a".
  • The N (a sed command) was used to read the next input line and appended it to the pattern space.
  • We used the $! condition to check if the current line was not the last input line.
  • The ba (a sed command) jumped to the label "a" that we defined using :a, creating a loop effectively.

Here, the ; was the separator, separating all commands from one another. Now, we used the s/ //g to remove all spaces in the modified single-line string and updated the var variable. Finally, we displayed it on the Bash console using the echo command.

Using tr Command

Use the tr command to remove all spaces from the specified string without modifying the original variable in Bash.

First, defined the var variable and set its value to = Java 2 Blog =. Next, we piped this variable to the tr command using a pipeline (|). The tr command is a utility used to translate or delete characters; we used it to delete all occurrences of the space characters from the input string.

We used the -d option to denote that we wanted to delete characters instead of translating them. Here, ' ' was an argument provided to the tr command, mentioning the character to be removed/deleted; in the above example, it was the space character. Finally, we used the echo command to display the modified string.

Use the tr command to remove all spaces from the given string and update the original variable in Bash.

We have already learned the tr command and the -d option in this section. While we have gone through the << You can use the shopt to allow extended globing if you don’t want to use POSIX compliant way.

shopt -s extglob; var=" Java 2 Blog "; echo "{var//+([[:space:]])/}"

Using Parameter Expansion

Use parameter expansion syntax to remove all spaces from the specified string without modifying the original variable in Bash.

We set the str variable with a string value. Then, we used the parameter expansion syntax ({var//[[:blank:]]/}) to update the value stored in the str variable. The [[:blank:]] was the character class we used to match the whitespace characters, including tabs and spaces.

The // after the str variable name represented that we wanted to replace all occurrences of the specified pattern with the given replacement. The replacement part was empty in the above code because we had nothing after the second /.

So, it matched all occurrences of whitespace characters and removed them effectively from the given input string, str. Here, the ${...} is the syntax for parameter expansion that we use in Bash. It allows us to manipulate the specified variables and substitutes their values within the strings. You can find more about parameter expansion here.

Finally, we used the echo command to print the modified string. Note that the value of the str variable was not updated. To do that, we must assign the modified string to the str variable as follows.

Use parameter expansion syntax to remove all spaces from the given string and update the original variable in Bash.

We learned how to remove all spaces from the given string with/without updating the original variable, but what if we have to eradicate all spaces from a multiline string? Let’s see the following code to learn how to do it.

Use parameter expansion syntax to remove all spaces from the multiline string. The output value must be a single-line string containing no space characters.

First, we set the multiline_str variable with a multiline string value. The ${multiline_str//[[:blank:]]/} was the parameter expansion syntax that we used to remove all spaces from the given string, which was multiline_str (we have learned this syntax with the first example in this section).

Then, we stored the modified string, returned by parameter expansion syntax, into the str variable. After that, we used echo "$str" to pass the value of the str variable to the tr command via pipeline. After that, the tr deleted all newline characters from the string.

The use of the tr command is explained in detail in the [Using tr Command](Add link here) section

We used the $(...) syntax to access the value returned by the echo "$str" | tr -d '\n' command and stored it in the single_line_str variable, which was further printed on the Bash console using echo command.

Now, how did we get a single-line string? We used parameter expansion to remove all occurrences of space characters, while the tr command was used to delete newline characters. This is how we got a single-line string without any space characters.

Using awk Command with gsub Function

Use the awk command with the gsub function to remove all spaces from the specified string without modifying the original variable in Bash.

Again, we set the var variable with a string value containing multiple space characters. The input string, the value of the var variable, was passed to the awk command using here-string (<<<). Then, we used the awk command to process the input; how? Let’s break it down below:

The gsub() function, gsub(/ /, "") within the awk command performed a global substitution of space characters (/ /) with an empty string (""). Then, output the modified string using the print command.

Finally, we used the $(...) substitution syntax to access the value returned by the awk command; this value was further printed on the Bash console using the echo command.

Use the awk command with the gsub function to remove all spaces from the given string and update the original variable in Bash.

Use the awk command with the gsub function to remove all spaces from the multiline string. The output value must be a single-line string containing no space characters.

This example code also resembles the last two code snippets, excluding the awk script, which differs slightly. Here, we used the printf "%s", $0 to print every updated line without a trailing new line. This kept all lines concatenated and resulted in a single-line string, which we assigned to the var variable. Finally, we printed the value of var using the echo command.

Using read Command

Use the read command to remove all spaces from the specified string without modifying the original variable in Bash.

First, we set the str_var with a string value having multiple whitespace characters. Then, we used the read command to read the value of the str_var variable, split them into separate words, and store them in the words array. Here, << You must explicitly set the value of IFS` if you don’t want to use a space character as a delimiter.

We also used -r and -a options with read where -r ensured that backslashes would not be treated as escape characters while -a specified the words should be stored in the words array.

Next, we used the printf command to format and print the items of the words array. Here, '%s' was specified to format every item of the array while "${words[@]}" expanded the items of the words array as individual arguments to the printf command.

Finally, we used the $(...) syntax to grab the output of the printf command and printed array on the Bash console using the echo command.

Use the read command to remove all spaces from the given string and update the original variable in Bash.

You can use the tr command or any of the above approaches to remove spaces from a multiline string.

Until now, we have explored various solutions to remove all spaces from the input string, but you may have a situation where the input string has multiple occurrences of the spaces rather than a single space. We use the xargs command-line utility to remove extra occurrences of space characters.

That’s all about Bash remove spaces from String.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *