Bash Shell Remove & Trim White Spaces From String / Variable

www.la‮u‬tturi.com
Bash Shell Remove & Trim White Spaces From String / Variable

To remove leading and trailing white space from a string in Bash, you can use the sed command:

$ sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<< " Hello world! "
Hello world!

This will remove any leading and trailing white space from the string, and print the resulting string to standard output.

If you want to remove all white space from a string, you can use the tr command:

$ tr -d ' ' <<< " Hello world! "
Helloworld!

This will remove all white space from the string, including spaces, tabs, and newlines, and print the resulting string to standard output.

To remove leading and trailing white space from a variable in Bash, you can use the sed command in combination with the var= syntax:

$ var=" Hello world! "
$ var=$(sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<< "$var")
$ echo "$var"
Hello world!

This will remove any leading and trailing white space from the var variable, and store the resulting string in the var variable. You can then use the echo command to print the value of the var variable to standard output.

Created Time:2017-10-16 14:38:38  Author:lautturi