have a bash variable as follows:
output="$(awk -F',' '/Name/ {print $9}' input.file)"
How do trim leading and trailing whitespace from bash variable called $output? How do I trim trailing whitespace from $output?
You can use sed, awk, cut, tr, and other utilities to remove whitespace from $output.
Tutorial details | |
---|---|
Difficulty | Easy (rss) |
Root privileges | No |
Requirements | Linux/Unix+Bash/Ksh |
Estimated completion time | N/A |
Define a variable called ouput:
output=" This is a test"
Use echo statement to display $output:
echo "=${output}="
Sample outputs:
= This is a test=
The syntax is:
echo "${output}" | sed -e 's/^[ \t]*//'
Sample outputs:
This is a test
The syntax is to remove leading whitespaces:
${var##*( )}
For example:
# Just remove leading whiltespace #turn it on shopt -s extglob output=" This is a test" output="${output##*( )}" echo "=${output}=" # turn it off shopt -u extglob
Sample outputs:
=This is a test=
To trim leading and trailing whitespace using bash, try:
#turn it on shopt -s extglob output=" This is a test " ### Trim leading whitespaces ### output="${output##*( )}" ### trim trailing whitespaces ## output="${output%%*( )} echo "=${output}=" # turn it off shopt -u extglob
Sample outputs:
=This is a test=
The syntax is:
output=" This is a test " echo "=${output}=" ## Use awk to trim leading and trailing whitespace echo "${output}" | awk '{gsub(/^ +| +$/,"")} {print "=" $0 "="}'
Sample outputs:
=This is a test=Facebook itG+ itDownload PDF versionFound an error/typo on this page?