To trim leading (left) and trailing (right) white space from a string in bash, you can use the sed
command.
The sed
command is a powerful utility for editing text in bash. It allows you to perform various text transformations, including trimming white space.
To trim leading and trailing white space from a string, you can use the sed
command with the s
(substitute) command and the following regular expression:
^[ \t]*|[ \t]*$
This regular expression matches any leading or trailing white space (spaces or tabs) in the string and replaces it with an empty string.
Here's an example of how you can use the sed
command to trim leading and trailing white space from a string in bash:
string=" This is a string with leading and trailing white space " trimmed_string=$(echo "$string" | sed 's/^[ \t]*|[ \t]*$//g') echo "$trimmed_string"
This will output the following string:
This is a string with leading and trailing white space
Note that the sed
command works on a line-by-line basis. If you want to trim leading and trailing white space from multiple lines of text, you can use the -n
option to suppress output and the p
command to print only the modified lines:
string=" This is a string with leading and trailing white space This is another string with leading and trailing white space " trimmed_string=$(echo "$string" | sed -n 's/^[ \t]*|[ \t]*$//gp') echo "$trimmed_string"
This will output the following text:
This is a string with leading and trailing white space This is another string with leading and trailing white space