user2093552
user2093552

Reputation: 1247

BASH - Simply to remove spaces before the first character and the last character

Simply to remove spaces before the first character and the last character

FOO="   ffs ff ssdf hfdh     hfghfghfgh hhgfg      "

result
ffs ff ssdf hfdh     hfghfghfgh hhgfg

Thank you

Upvotes: 2

Views: 3090

Answers (4)

ormaaj
ormaaj

Reputation: 6617

Assuming the goal is to modify the variable (in order of decreasing portability):

# POSIX
foo=${foo#"${foo%%[! ]*}"} foo=${foo%"${foo##*[! ]}"}

# Bash/ksh
${BASH_VERSION+'false'} || shopt -s extglob
foo=${foo##+( )} foo=${foo%%+( )}

# Bash4/ksh
IFS=' ' read -rd '' foo < <(printf %s "$foo")

# Bash4/ksh93
${KSH_VERSION+'false'} || typeset -n BASH_REMATCH=.sh.match
[[ $foo =~ ^\ *([! ].*[! ])\ *$ ]]
foo=${BASH_REMATCH[1]}

# ksh93
foo=${foo/~(K)*(\ )@([! ]*[! ])*(\ )/\2}

As usual it's impossible to recommend a best approach without knowing both what you're starting with and what you want to do with the result.

Upvotes: 5

bruce_ricard
bruce_ricard

Reputation: 771

echo $FOO | sed 's/^ *//' | sed 's/ *$//'

Upvotes: 0

Vetsin
Vetsin

Reputation: 2612

echo "   ffs ff ssdf hfdh     hfghfghfgh hhgfg      " | sed -e 's/^ *//g' -e 's/ *$//g'

Upvotes: 2

Eric Johnson
Eric Johnson

Reputation: 826

If you are using bash v4, then this should work for you.

FOO=${FOO:1:-1}

Upvotes: 0

Related Questions