Re: Trimming leading and trailing blanks from a string
From:
Greg Wooledge
Subject:
Re: Trimming leading and trailing blanks from a string
Date:
Thu, 5 Feb 2026 15:52:22 -0500
User-agent:
Mutt/1.10.1 (2018-07-13)
On Thu, Feb 05, 2026 at 15:18:08 -0500, Zachary Santer wrote:
> On Thu, Feb 5, 2026 at 10:35 AM Stan Marsh <gazelle@xmission.com> wrote:
> > [[ $foo =~ [^[:space:]](.*[^[:space:]])? ]]
> >
> > leaves the result in $BASH_REMATCH.
> >
> > The above will generate an (trappable/expected) error if the resulting
> > string is empty.
>
> I've done something similar to remove trailing whitespace and only
> match when there was trailing whitespace to remove:
>
> strip_trailing_whitespace_regex='^(.*[^[:blank:]])?[[:blank:]]+$'
> REMAINING_LINE_CG=1
> if [[ ${line} =~ ${strip_trailing_whitespace_regex} ]]; then
> printf '|%s|\n' "${BASH_REMATCH[REMAINING_LINE_CG]}"
> fi
<https://mywiki.wooledge.org/BashFAQ/067> has several more methods,
including a 4-step method that works in POSIX sh. Here are the first
two methods from the wiki page, for the lazy reader:
# POSIX
junk=${var%%[! ]*} # remove all but leading spaces
var=${var#"$junk"} # remove leading spaces from original string
junk=${var##*[! ]} # remove all but trailing spaces
var=${var%"$junk"} # remove trailing spaces from original string
# Bash
shopt -s extglob
var=${var##*( )} # trim the left
var=${var%%*( )} # trim the right