Bash Shell: Trim Leading White Space From Input Variables

Bash Shell: Trim Leading White Space From Input Variables

To trim leading white space (spaces and tabs) from input variables in a Bash shell script, you can use the sed command with the s/^[ \t]*// command.

For example, to trim leading white space from a variable named FOO, you can use the following command:

FOO=$(echo $FOO | sed 's/^[ \t]*//')
Source:ww‮tual.w‬turi.com

This will use the sed command to remove all leading spaces and tabs from the FOO variable and store the result in the FOO variable.

The s/^[ \t]*// command tells sed to remove all leading spaces and tabs ([ \t]*) from the input. The ^ character specifies the beginning of the input, and the * character specifies zero or more occurrences of the preceding character class ([ \t]).

You can also use the awk command to trim leading white space from a variable. For example:

FOO=$(echo $FOO | awk '{$1=$1};1')

This will use the awk command to remove all leading spaces and tabs from the FOO variable and store the result in the FOO variable.

The {$1=$1};1 command tells awk to reassign the first field ($1) to itself, which has the effect of trimming leading white space from the field. The 1 at the end tells awk to print the modified input.

You can also use the sed or awk commands to trim leading white space from multiple variables at once. For example:

FOO=$(echo $FOO | sed 's/^[ \t]*//')
BAR=$(echo $BAR | sed 's/^[ \t]*//')
BAZ=$(echo $BAZ | sed 's/^[ \t]*//')

This will trim leading white space from the FOO, BAR, and BAZ variables using the sed command.

Keep in mind that these commands will only trim leading white space from the input variables. To trim trailing white space or to trim white space from both the beginning and the end of the variables, you will need to use a different approach.

Created Time:2017-10-27 14:56:35  Author:lautturi