$ var='abc def'$ echo "$var"abc def# Note: flussence's original expression was "${var/ /}", which only replaced the *first* space char., wherever it appeared.$ echo -n "${var//[[:space:]]/}"abcdef
FOO=' test test test 'echo -e "FOO='${FOO}'"# > FOO=' test test test 'echo -e "length(FOO)==${#FOO}"# > length(FOO)==16
如何删除所有空格(由tr中的[:space:]表示):
FOO=' test test test 'FOO_NO_WHITESPACE="$(echo -e "${FOO}" | tr -d '[:space:]')"echo -e "FOO_NO_WHITESPACE='${FOO_NO_WHITESPACE}'"# > FOO_NO_WHITESPACE='testtesttest'echo -e "length(FOO_NO_WHITESPACE)==${#FOO_NO_WHITESPACE}"# > length(FOO_NO_WHITESPACE)==12
如何仅删除前导空格:
FOO=' test test test 'FOO_NO_LEAD_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//')"echo -e "FOO_NO_LEAD_SPACE='${FOO_NO_LEAD_SPACE}'"# > FOO_NO_LEAD_SPACE='test test test 'echo -e "length(FOO_NO_LEAD_SPACE)==${#FOO_NO_LEAD_SPACE}"# > length(FOO_NO_LEAD_SPACE)==15
如何仅删除尾随空格:
FOO=' test test test 'FOO_NO_TRAIL_SPACE="$(echo -e "${FOO}" | sed -e 's/[[:space:]]*$//')"echo -e "FOO_NO_TRAIL_SPACE='${FOO_NO_TRAIL_SPACE}'"# > FOO_NO_TRAIL_SPACE=' test test test'echo -e "length(FOO_NO_TRAIL_SPACE)==${#FOO_NO_TRAIL_SPACE}"# > length(FOO_NO_TRAIL_SPACE)==15
如何删除前导和尾随空格——链接sed:
FOO=' test test test 'FOO_NO_EXTERNAL_SPACE="$(echo -e "${FOO}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"echo -e "FOO_NO_EXTERNAL_SPACE='${FOO_NO_EXTERNAL_SPACE}'"# > FOO_NO_EXTERNAL_SPACE='test test test'echo -e "length(FOO_NO_EXTERNAL_SPACE)==${#FOO_NO_EXTERNAL_SPACE}"# > length(FOO_NO_EXTERNAL_SPACE)==14
或者,如果您的bash支持它,您可以将echo -e "${FOO}" | sed ...替换为sed ... <<<${FOO},如下所示(用于尾随空格):
#!/bin/bashfunction trim {echo $*}
echo "'$(trim " one two three ")'"# 'one two three'
另一个使用正则表达式的变体。
#!/bin/bashfunction trim {local trimmed="$@"if [[ "$trimmed" =~ " *([^ ].*[^ ]) *" ]]thentrimmed=${BASH_REMATCH[1]}fiecho "$trimmed"}
echo "'$(trim " one two three ")'"# 'one two three'
#Turn on extended globbingshopt -s extglob#Trim leading and trailing whitespace from a variablex=${x##+([[:space:]])}; x=${x%%+([[:space:]])}#Turn off extended globbingshopt -u extglob
这是包装在函数中的相同功能(注意:需要引用传递给函数的输入字符串):
trim() {# Determine if 'extglob' is currently on.local extglobWasOff=1shopt extglob >/dev/null && extglobWasOff=0(( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off.# Trim leading and trailing whitespacelocal var=$1var=${var##+([[:space:]])}var=${var%%+([[:space:]])}(( extglobWasOff )) && shopt -u extglob # If 'extglob' was off before, turn it back off.echo -n "$var" # Output trimmed string.}
用法:
string=" abc def ghi ";#need to quote input-string to preserve internal white-space if anytrimmed=$(trim "$string");echo "$trimmed";
#!/bin/bash
function trim{typeset trimVareval trimVar="\${$1}"read trimVar << EOTtrim$trimVarEOTtrimeval $1=\$trimVar}
# Note that the parameter to the function is the NAME of the variable to trim,# not the variable contents. However, the contents are trimmed.
# Example of use:while read aLinedotrim alineecho "[${aline}]"done < info.txt
# File info.txt contents:# ------------------------------# ok hello there $# another line here $#and yet another $# only at the front$#$
# Output:#[ok hello there]#[another line here]#[and yet another]#[only at the front]#[]
var="$(hg st -R "$path")" # I often like to enclose shell output in double quotesvar="$(echo "${var}" | sed "s/\(^ *\| *\$\)//g")" # This is my suggestionif [ -n "$var" ]; thenecho "[${var}]"fi
'ses'命令仅修剪前导和尾随空格,但它也可以通过管道传输到第一个命令,从而导致:
var="$(hg st -R "$path" | sed "s/\(^ *\| *\$\)//g")"if [ -n "$var" ]; thenecho "[${var}]"fi
string=' wordAA>four spaces before<>one space before< 'echo "$string" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'
输出:
wordAA>four spaces before<>one space before<
因此,如果您确实介意保留这些空格,请使用我答案开头的函数!
在函数trim中使用的多行字符串上的se语法“查找和替换”的(d)解释:
sed -n '# If the first line, copy the pattern to the hold buffer1h# If not the first line, then append the pattern to the hold buffer1!H# If the last line then ...$ {# Copy from the hold to the pattern bufferg# Do the search and replaces/^[ \t]*//gs/[ \t]*$//g# printp}'
#Execute this script with the string argument passed in double quotes !!#var2 gives the string without spaces.#$1 is the string passed in double quotes#!/bin/bashvar2=`echo $1 | sed 's/ \+//g'`echo $var2
if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]thentest=${BASH_REMATCH[1]}fi
这是一个用于测试它的示例脚本:
test=$(echo -e "\n \t Spaces and tabs and newlines be gone! \t \n ")
echo "Let's see if this works:"echoecho "----------"echo -e "Testing:${test} :Tested" # Ugh!echo "----------"echoecho "Ugh! Let's fix that..."
if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]thentest=${BASH_REMATCH[1]}fi
echoecho "----------"echo -e "Testing:${test}:Tested" # "Testing:Spaces and tabs and newlines be gone!"echo "----------"echoecho "Ah, much better."
text=" trim my edges "
trimmed=$texttrimmed=${trimmed##+( )} #Remove longest matching series of spaces from the fronttrimmed=${trimmed%%+( )} #Remove longest matching series of spaces from the back
echo "<$trimmed>" #Adding angle braces just to make it easier to confirm that all spaces are removed
#Result<trim my edges>
将其放在更少的行上以获得相同的结果:
text=" trim my edges "trimmed=${${text##+( )}%%+( )}
#!/bin/bash
. trim.sh
enum() {echo " a b c"echo "a b c "echo " a b c "echo " a b c "echo " a b c "echo " a b c "echo " a b c "echo " a b c "echo " a b c "echo " a b c "echo " a b c "echo " a N b c "echo "N a N b c "echo " Na b c "echo " a b c N "echo " a b c N"}
xcheck() {local testln resultwhile IFS='' read testln;dotestln=$(tr N '\n' <<<"$testln")echo ": ~~~~~~~~~~~~~~~~~~~~~~~~~ :" >&2result="$(trim "$testln")"echo "testln='$testln'" >&2echo "result='$result'" >&2done}
enum | xcheck
# Strip leading and trailing white space (new line inclusive).trim(){[[ "$1" =~ [^[:space:]](.*[^[:space:]])? ]]printf "%s" "$BASH_REMATCH"}
或
# Strip leading white space (new line inclusive).ltrim(){[[ "$1" =~ [^[:space:]].* ]]printf "%s" "$BASH_REMATCH"}
# Strip trailing white space (new line inclusive).rtrim(){[[ "$1" =~ .*[^[:space:]] ]]printf "%s" "$BASH_REMATCH"}
# Strip leading and trailing white space (new line inclusive).trim(){printf "%s" "$(rtrim "$(ltrim "$1")")"}
# Strip leading and trailing white space (new line inclusive).trim(){printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)[[:space:]]*$"`"}
或
# Strip leading white space (new line inclusive).ltrim(){printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)"`"}
# Strip trailing white space (new line inclusive).rtrim(){printf "%s" "`expr "$1" : "^\(.*[^[:space:]]\)[[:space:]]*$"`"}
# Strip leading and trailing white space (new line inclusive).trim(){printf "%s" "$(rtrim "$(ltrim "$1")")"}
line=${line##+([[:space:]])} # strip leading whitespace; no quote expansion!line=${line%%+([[:space:]])} # strip trailing whitespace; no quote expansion!line=${line//[[:space:]]/} # strip all whitespaceline=${line//[[:space:]]/} # strip all whitespace
line=${line//[[:blank:]]/} # strip all blank space