如何从Bash变量中修剪空格?

时间:2008-12-15 21:24:01

标签: string bash variables trim

我有一个包含以下代码的shell脚本:

var=`hg st -R "$path"`
if [ -n "$var" ]; then
    echo $var
fi

但条件代码总是执行,因为hg st总是打印至少一个换行符。

  • 是否有一种简单的方法可以从$var中删除空格(如PHP中的trim())?

  • 是否有处理此问题的标准方法?

我可以使用sedAWK,但我想认为这个问题有一个更优雅的解决方案。

44 个答案:

答案 0 :(得分:914)

让我们定义一个包含前导,尾随和中间空格的变量:

FOO=' test test test '
echo -e "FOO='${FOO}'"
# > FOO=' test test test '
echo -e "length(FOO)==${#FOO}"
# > length(FOO)==16

如何删除[:space:]中的所有空格(由tr表示):

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 s:

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},就像这样(对于尾随空格):

FOO_NO_TRAIL_SPACE="$(sed -e 's/[[:space:]]*$//' <<<${FOO})"

答案 1 :(得分:795)

一个简单的答案是:

echo "   lol  " | xargs

Xargs会为你修剪。它是一个命令/程序,没有参数,返回修剪后的字符串,就这么简单!

注意:这不会删除内部空格,因此"foo bar"保持不变。它不会成为"foobar"

答案 2 :(得分:293)

有一个解决方案只使用名为通配符的Bash内置函数:

var="    abc    "
# remove leading whitespace characters
var="${var#"${var%%[![:space:]]*}"}"
# remove trailing whitespace characters
var="${var%"${var##*[![:space:]]}"}"   
echo "===$var==="

这是函数中的相同内容:

trim() {
    local var="$*"
    # remove leading whitespace characters
    var="${var#"${var%%[![:space:]]*}"}"
    # remove trailing whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   
    echo -n "$var"
}

您以引用的形式传递要剪裁的字符串。例如:

trim "   abc   "

这个解决方案的一个好处是它可以与任何符合POSIX标准的shell一起使用。

参考

答案 3 :(得分:68)

Bash有一个名为参数扩展的功能,除其他外,它允许基于所谓的模式进行字符串替换(模式类似于正则表达式,但有基本的差异和局限)。 [flussence的原始行:Bash有正则表达式,但它们隐藏得很好:]

以下演示如何从变量值中删除所有空白区域(甚至是内部空间)。

$ 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

答案 4 :(得分:46)

剥去一个前导空格和一个尾随空格

trim()
{
    local trimmed="$1"

    # Strip leading space.
    trimmed="${trimmed## }"
    # Strip trailing space.
    trimmed="${trimmed%% }"

    echo "$trimmed"
}

例如:

test1="$(trim " one leading")"
test2="$(trim "one trailing ")"
test3="$(trim " one leading and one trailing ")"
echo "'$test1', '$test2', '$test3'"

输出:

'one leading', 'one trailing', 'one leading and one trailing'

剥离所有前导和尾随空格

trim()
{
    local trimmed="$1"

    # Strip leading spaces.
    while [[ $trimmed == ' '* ]]; do
       trimmed="${trimmed## }"
    done
    # Strip trailing spaces.
    while [[ $trimmed == *' ' ]]; do
        trimmed="${trimmed%% }"
    done

    echo "$trimmed"
}

例如:

test4="$(trim "  two leading")"
test5="$(trim "two trailing  ")"
test6="$(trim "  two leading and two trailing  ")"
echo "'$test4', '$test5', '$test6'"

输出:

'two leading', 'two trailing', 'two leading and two trailing'

答案 5 :(得分:36)

您只需使用echo

即可修剪
foo=" qsdqsd qsdqs q qs   "

# Not trimmed
echo \'$foo\'

# Trim
foo=`echo $foo`

# Trimmed
echo \'$foo\'

答案 6 :(得分:35)

来自globbing

的Bash指南部分

在参数扩展中使用extglob

 #Turn on extended globbing  
shopt -s extglob  
 #Trim leading and trailing whitespace from a variable  
x=${x##+([[:space:]])}; x=${x%%+([[:space:]])}  
 #Turn off extended globbing  
shopt -u extglob  

这是函数中包含的相同功能(注意:需要引用传递给函数的输入字符串):

trim() {
    # Determine if 'extglob' is currently on.
    local extglobWasOff=1
    shopt extglob >/dev/null && extglobWasOff=0 
    (( extglobWasOff )) && shopt -s extglob # Turn 'extglob' on, if currently turned off.
    # Trim leading and trailing whitespace
    local var=$1
    var=${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 any
trimmed=$(trim "$string");  
echo "$trimmed";

如果我们改变要在子shell中执行的函数,我们不必担心检查extglob的当前shell选项,我们可以在不影响当前shell的情况下设置它。这极大地简化了功能。我还“就地”更新位置参数,所以我甚至不需要局部变量

trim() {
    shopt -s extglob
    set -- "${1##+([[:space:]])}"
    printf "%s" "${1%%+([[:space:]])}" 
}

这样:

$ s=$'\t\n \r\tfoo  '
$ shopt -u extglob
$ shopt extglob
extglob         off
$ printf ">%q<\n" "$s" "$(trim "$s")"
>$'\t\n \r\tfoo  '<
>foo<
$ shopt extglob
extglob         off

答案 7 :(得分:24)

启用Bash的扩展模式匹配功能(shopt -s extglob)后,您可以使用:

{trimmed##*( )}

删除任意数量的前导空格。

答案 8 :(得分:20)

您可以使用tr删除换行符:

var=`hg st -R "$path" | tr -d '\n'`
if [ -n $var ]; then
    echo $var
done

答案 9 :(得分:20)

我总是用sed

完成它
  var=`hg st -R "$path" | sed -e 's/  *$//'`

如果有一个更优雅的解决方案,我希望有人发布它。

答案 10 :(得分:17)

# Trim whitespace from both ends of specified parameter

trim () {
    read -rd '' $1 <<<"${!1}"
}

# Unit test for trim()

test_trim () {
    local foo="$1"
    trim foo
    test "$foo" = "$2"
}

test_trim hey hey &&
test_trim '  hey' hey &&
test_trim 'ho  ' ho &&
test_trim 'hey ho' 'hey ho' &&
test_trim '  hey  ho  ' 'hey  ho' &&
test_trim $'\n\n\t hey\n\t ho \t\n' $'hey\n\t ho' &&
test_trim $'\n' '' &&
test_trim '\n' '\n' &&
echo passed

答案 11 :(得分:11)

您可以使用老派tr。例如,这将返回git存储库中已修改文件的数量,这些空格被剥离。

MYVAR=`git ls-files -m|wc -l|tr -d ' '`

答案 12 :(得分:11)

有很多答案,但我仍然相信我的刚写的脚本值得一提,因为:

  • 它已在shell bash / dash / busybox shell中成功测试
  • 非常小
  • 它不依赖于外部命令,也不需要fork( - &gt;快速和低资源使用)
  • 它按预期工作:
    • 它从开头和结尾剥离所有空格和制表符,但不是更多
    • 很重要:它不会从字符串中间删除任何内容(许多其他答案都会删除),即使换行也会保留
    • special:"$*"使用一个空格连接多个参数。如果你想修剪和仅输出第一个参数,使用"$1"代替
    • 如果匹配文件名模式等没有任何问题

剧本:

trim() {
  local s2 s="$*"
  # note: the brackets in each of the following two lines contain one space
  # and one tab
  until s2="${s#[   ]}"; [ "$s2" = "$s" ]; do s="$s2"; done
  until s2="${s%[   ]}"; [ "$s2" = "$s" ]; do s="$s2"; done
  echo "$s"
}

用法:

mystring="   here     is
    something    "
mystring=$(trim "$mystring")
echo ">$mystring<"

输出:

>here     is
    something<

答案 13 :(得分:9)

# Strip leading and trailing white space (new line inclusive).
trim(){
    [[ "$1" =~ [^[:space:]](.*[^[:space:]])? ]]
    printf "%s" "$BASH_REMATCH"
}

OR

# 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")")"
}

OR

# Strip leading and trailing specified characters.  ex: str=$(trim "$str" $'\n a')
trim(){
    if [ "$2" ]; then
        trim_chrs="$2"
    else
        trim_chrs="[:space:]"
    fi

    [[ "$1" =~ ^["$trim_chrs"]*(.*[^"$trim_chrs"])["$trim_chrs"]*$ ]]
    printf "%s" "${BASH_REMATCH[1]}"
}

OR

# Strip leading specified characters.  ex: str=$(ltrim "$str" $'\n a')
ltrim(){
    if [ "$2" ]; then
        trim_chrs="$2"
    else
        trim_chrs="[:space:]"
    fi

    [[ "$1" =~ ^["$trim_chrs"]*(.*[^"$trim_chrs"]) ]]
    printf "%s" "${BASH_REMATCH[1]}"
}

# Strip trailing specified characters.  ex: str=$(rtrim "$str" $'\n a')
rtrim(){
    if [ "$2" ]; then
        trim_chrs="$2"
    else
        trim_chrs="[:space:]"
    fi

    [[ "$1" =~ ^(.*[^"$trim_chrs"])["$trim_chrs"]*$ ]]
    printf "%s" "${BASH_REMATCH[1]}"
}

# Strip leading and trailing specified characters.  ex: str=$(trim "$str" $'\n a')
trim(){
    printf "%s" "$(rtrim "$(ltrim "$1" "$2")" "$2")"
}

OR

以moskit的expr soulution为基础......

# Strip leading and trailing white space (new line inclusive).
trim(){
    printf "%s" "`expr "$1" : "^[[:space:]]*\(.*[^[:space:]]\)[[:space:]]*$"`"
}

OR

# 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")")"
}

答案 14 :(得分:9)

这对我有用:

text="   trim my edges    "

trimmed=$text
trimmed=${trimmed##+( )} #Remove longest matching series of spaces from the front
trimmed=${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##+( )}%%+( )}

答案 15 :(得分:8)

我见过脚本只是使用变量赋值来完成这项工作:

$ xyz=`echo -e 'foo \n bar'`
$ echo $xyz
foo bar

自动合并和修剪空白。人们必须小心壳元元素(潜在的注入风险)。

我还建议在shell条件中始终双引用变量替换:

if [ -n "$var" ]; then

因为变量中的-o或其他内容可能会修改您的测试参数。

答案 16 :(得分:7)

var='   a b c   '
trimmed=$(echo $var)

答案 17 :(得分:7)

我只想使用sed:

function trim
{
    echo "$1" | sed -n '1h;1!H;${;g;s/^[ \t]*//g;s/[ \t]*$//g;p;}'
}

a)单行字符串的使用示例

string='    wordA wordB  wordC   wordD    '
trimmed=$( trim "$string" )

echo "GIVEN STRING: |$string|"
echo "TRIMMED STRING: |$trimmed|"

输出:

GIVEN STRING: |    wordA wordB  wordC   wordD    |
TRIMMED STRING: |wordA wordB  wordC   wordD|

b)多行字符串的使用示例

string='    wordA
   >wordB<
wordC    '
trimmed=$( trim "$string" )

echo -e "GIVEN STRING: |$string|\n"
echo "TRIMMED STRING: |$trimmed|"

输出:

GIVEN STRING: |    wordAA
   >wordB<
wordC    |

TRIMMED STRING: |wordAA
   >wordB<
wordC|

c)最后说明:
如果您不想使用函数,对于单行字符串,您只需使用“更容易记住”的命令,如:

echo "$string" | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'

示例:

echo "   wordA wordB wordC   " | sed -e 's/^[ \t]*//' | sed -e 's/[ \t]*$//'

输出:

wordA wordB wordC

多行字符串上使用上述内容也可以正常使用,但请注意它也会删除任何尾随/前导内部多个空格,正如GuruM在评论中注意到的那样

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<

因此,如果您考虑保留这些空格,请在我的答案开头使用该功能!

d)在函数trim中使用的多行字符串上的sed语法“find and replace”的EXPLANATION

sed -n '
# If the first line, copy the pattern to the hold buffer
1h
# If not the first line, then append the pattern to the hold buffer
1!H
# If the last line then ...
$ {
    # Copy from the hold to the pattern buffer
    g
    # Do the search and replace
    s/^[ \t]*//g
    s/[ \t]*$//g
    # print
    p
}'

答案 18 :(得分:6)

分配忽略前导和尾随空格,因此可用于修剪:

$ var=`echo '   hello'`; echo $var
hello

答案 19 :(得分:5)

这是一个trim()函数,用于修剪和标准化空格

#!/bin/bash
function trim {
    echo $*
}

echo "'$(trim "  one   two    three  ")'"
# 'one two three'

另一种使用正则表达式的变体。

#!/bin/bash
function trim {
    local trimmed="$@"
    if [[ "$trimmed" =~ " *([^ ].*[^ ]) *" ]]
    then 
        trimmed=${BASH_REMATCH[1]}
    fi
    echo "$trimmed"
}

echo "'$(trim "  one   two    three  ")'"
# 'one   two    three'

答案 20 :(得分:5)

使用AWK:

echo $var | awk '{gsub(/^ +| +$/,"")}1'

答案 21 :(得分:5)

要从左侧删除空格和制表符,请输入:

echo "     This is a test" | sed "s/^[ \t]*//"

cyberciti.biz/tips/delete-leading-spaces-from-front-of-each-word.html

答案 22 :(得分:4)

这将删除String中的所有空格

 VAR2="${VAR2//[[:space:]]/}"

/替换字符串中第一次出现和//所有出现的空格。即所有白色空间都被 - 没有

取代

答案 23 :(得分:4)

这是我见过的最简单的方法。它只使用Bash,它只有几行,正则表达式很简单,它匹配所有形式的空白:

if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]
then 
    test=${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:"
echo
echo "----------"
echo -e "Testing:${test} :Tested"  # Ugh!
echo "----------"
echo
echo "Ugh!  Let's fix that..."

if [[ "$test" =~ ^[[:space:]]*([^[:space:]].*[^[:space:]])[[:space:]]*$ ]]
then 
    test=${BASH_REMATCH[1]}
fi

echo
echo "----------"
echo -e "Testing:${test}:Tested"  # "Testing:Spaces and tabs and newlines be gone!"
echo "----------"
echo
echo "Ah, much better."

答案 24 :(得分:4)

这不包含不需要的globbing问题,内部空白也未修改(假设$IFS设置为默认值,即' \t\n')。

它会读取第一个换行符(并且不包含它)或字符串的结尾(以先到者为准),并删除前导和尾随空格以及\t个字符的任意组合。如果要保留多行(并且还要删除前导和尾随换行符),请改用read -r -d '' var << eof;但请注意,如果您的输入恰好包含\neof,则会在之前将其切断。 (其他形式的空格,即\r\f\v被剥离,即使您将它们添加到$ IFS。)

read -r var << eof
$var
eof

答案 25 :(得分:3)

trim()删除空格(和制表符,不可打印的字符;为简单起见,我只考虑空白)。我的解决方案版本:

var="$(hg st -R "$path")" # I often like to enclose shell output in double quotes
var="$(echo "${var}" | sed "s/\(^ *\| *\$\)//g")" # This is my suggestion
if [ -n "$var" ]; then
 echo "[${var}]"
fi

'sed'命令仅修剪前导空格和尾随空格,但也可以通过管道传输给第一个命令,结果是:

var="$(hg st -R "$path" | sed "s/\(^ *\| *\$\)//g")"
if [ -n "$var" ]; then
 echo "[${var}]"
fi

答案 26 :(得分:3)

我发现我需要从凌乱的sdiff输出中添加一些代码才能清理它:

sdiff -s column1.txt column2.txt | grep -F '<' | cut -f1 -d"<" > c12diff.txt 
sed -n 1'p' c12diff.txt | sed 's/ *$//g' | tr -d '\n' | tr -d '\t'

这将删除尾随空格和其他不可见字符。

答案 27 :(得分:3)

我创建了以下功能。我不确定printf是多么便携,但这个解决方案的优点是你可以通过添加更多字符代码来准确指定什么是“空白区域”。

    iswhitespace()
    {
        n=`printf "%d\n" "'$1'"`
        if (( $n != "13" )) && (( $n != "10" )) && (( $n != "32" )) && (( $n != "92" )) && (( $n != "110" )) && (( $n != "114" )); then
            return 0
        fi
        return 1
    }

    trim()
    {
        i=0
        str="$1"
        while (( i < ${#1} ))
        do
            char=${1:$i:1}
            iswhitespace "$char"
            if [ "$?" -eq "0" ]; then
                str="${str:$i}"
                i=${#1}
            fi
            (( i += 1 ))
        done
        i=${#str}
        while (( i > "0" ))
        do
            (( i -= 1 ))
            char=${str:$i:1}
            iswhitespace "$char"
            if [ "$?" -eq "0" ]; then
                (( i += 1 ))
                str="${str:0:$i}"
                i=0
            fi
        done
        echo "$str"
    }

#Call it like so
mystring=`trim "$mystring"`

答案 28 :(得分:3)

Python有一个函数strip()与PHP的trim()完全相同,所以我们可以做一些内联Python,为此创建一个易于理解的实用程序:

alias trim='python -c "import sys; sys.stdout.write(sys.stdin.read().strip())"'

这将修剪前导和尾随空格(包括换行符)。

$ x=`echo -e "\n\t   \n" | trim`
$ if [ -z "$x" ]; then echo hi; fi
hi

答案 29 :(得分:3)

#!/bin/bash

function trim
{
    typeset trimVar
    eval trimVar="\${$1}"
    read trimVar << EOTtrim
    $trimVar
EOTtrim
    eval $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 aLine
do
    trim aline
    echo "[${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]
#[]

答案 30 :(得分:3)

使用:

trim() {
    local orig="$1"
    local trmd=""
    while true;
    do
        trmd="${orig#[[:space:]]}"
        trmd="${trmd%[[:space:]]}"
        test "$trmd" = "$orig" && break
        orig="$trmd"
    done
    printf -- '%s\n' "$trmd"
}
  • 适用于所有类型的空白,包括换行符,
  • 不需要修改shopt。
  • 它保留了内部空白,包括换行符。

单元测试(用于人工审核):

#!/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 result
    while IFS='' read testln;
    do
        testln=$(tr N '\n' <<<"$testln")
        echo ": ~~~~~~~~~~~~~~~~~~~~~~~~~ :" >&2
        result="$(trim "$testln")"
        echo "testln='$testln'" >&2
        echo "result='$result'" >&2
    done
}

enum | xcheck

答案 31 :(得分:2)

使用:

var=`expr "$var" : "^\ *\(.*[^ ]\)\ *$"`

它删除了前导和尾随空格,是我认为最基本的解决方案。不是Bash内置的,但'expr'是coreutils的一部分,因此至少不需要像sedAWK那样的独立实用程序。

答案 32 :(得分:2)

使用这个简单的Bash 参数扩展

$ x=" a z     e r ty "
$ echo "START[${x// /}]END"
START[azerty]END

答案 33 :(得分:2)

var="  a b  "
echo "$(set -f; echo $var)"

>a b

答案 34 :(得分:2)

IFS变量设置为其他内容时,我需要从脚本中修剪空格。依靠Perl做了诀窍:

# trim() { echo $1; } # This doesn't seem to work, as it's affected by IFS

trim() { echo "$1" | perl -p -e 's/^\s+|\s+$//g'; }

strings="after --> , <-- before,  <-- both -->  "

OLD_IFS=$IFS
IFS=","
for str in ${strings}; do
  str=$(trim "${str}")
  echo "str= '${str}'"
done
IFS=$OLD_IFS

答案 35 :(得分:2)

这会修剪前端和后端的多个空格

whatever=${whatever%% *}

whatever=${whatever#* }

答案 36 :(得分:2)

将空格移至一个空格:

(text) | fmt -su

答案 37 :(得分:1)

带有Yet another solution的{p> unit tests从stdin中修剪$IFS,并且可以使用任何输入分隔符(甚至是$'\0'):

ltrim()
{
    # Left-trim $IFS from stdin as a single line
    # $1: Line separator (default NUL)
    local trimmed
    while IFS= read -r -d "${1-}" -u 9
    do
        if [ -n "${trimmed+defined}" ]
        then
            printf %s "$REPLY"
        else
            printf %s "${REPLY#"${REPLY%%[!$IFS]*}"}"
        fi
        printf "${1-\x00}"
        trimmed=true
    done 9<&0

    if [[ $REPLY ]]
    then
        # No delimiter at last line
        if [ -n "${trimmed+defined}" ]
        then
            printf %s "$REPLY"
        else
            printf %s "${REPLY#"${REPLY%%[!$IFS]*}"}"
        fi
    fi
}

rtrim()
{
    # Right-trim $IFS from stdin as a single line
    # $1: Line separator (default NUL)
    local previous last
    while IFS= read -r -d "${1-}" -u 9
    do
        if [ -n "${previous+defined}" ]
        then
            printf %s "$previous"
            printf "${1-\x00}"
        fi
        previous="$REPLY"
    done 9<&0

    if [[ $REPLY ]]
    then
        # No delimiter at last line
        last="$REPLY"
        printf %s "$previous"
        if [ -n "${previous+defined}" ]
        then
            printf "${1-\x00}"
        fi
    else
        last="$previous"
    fi

    right_whitespace="${last##*[!$IFS]}"
    printf %s "${last%$right_whitespace}"
}

trim()
{
    # Trim $IFS from individual lines
    # $1: Line separator (default NUL)
    ltrim ${1+"$@"} | rtrim ${1+"$@"}
}

答案 38 :(得分:1)

这就是我所做的,并且完美而简单地完成了工作:

the_string="        test"
the_string=`echo $the_string`
echo "$the_string"

输出:

test

答案 39 :(得分:1)

数组赋值在 Internal Field Separator(默认为空格/制表符/换行符)上扩展其参数拆分。

words=($var)
var="${words[@]}"

答案 40 :(得分:0)

我必须从命令测试结果(数字),但是结果的变量似乎包含空格和一些不可打印的字符。因此,即使在“修剪”之后,该比较也是错误的。 我通过从变量中提取数字部分来解决它:

var tempImage = new Image();
tempImage.onload = new function() {
  console.log('image loaded');
};
tempImage.src = url;

答案 41 :(得分:0)

“trim”函数删除所有水平空白:

ltrim () {
    if [[ $# -eq 0 ]]; then cat; else printf -- '%s\n' "$@"; fi | perl -pe 's/^\h+//g'
    return $?
}

rtrim () {
    if [[ $# -eq 0 ]]; then cat; else printf -- '%s\n' "$@"; fi | perl -pe 's/\h+$//g'
    return $?
}

trim () {
    ltrim "$@" | rtrim
    return $?
}

答案 42 :(得分:-2)

虽然它不是严格意义上的Bash,但它会做你想要的和更多:

php -r '$x = trim("  hi there  "); echo $x;'

如果您想将其设为小写,请执行以下操作:

php -r '$x = trim("  Hi There  "); $x = strtolower($x) ; echo $x;'

答案 43 :(得分:-4)

#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/bash
var2=`echo $1 | sed 's/ \+//g'`
echo $var2