【问题标题】:Delete the word whose length is less than 2 in bash删除bash中长度小于2的单词
【发布时间】:2010-12-11 16:30:05
【问题描述】:

我在 CentOS 5.5 上使用 bash。我有一个用空格分隔的字符串,该字符串只包含字母和数字,而且这个字符串可能有多余的空格,例如"words""string"之间有1个以上的空格:

$exmple= "This is a lovey 7 words   string"

我想删除长度小于2的单词,本例中需要删除单词"a""7"。并删除所有多余的空格,一个单词和另一个单词之间只有一个空格。

所以字符串变成:

"This is lovey words string"

【问题讨论】:

    标签: linux bash command-line


    【解决方案1】:

    编辑(基于 ennukiller 的 sed 答案)

    使用纯 Bash:

    newstring=${exmple// ? / }   # remove one character words
    

    标准化空白:

    read newstring <<< $newstring
    

    shopt -s extglob
    newstring=${newstring//+( )/ }
    

    原文:

    exmple="This is a lovey 7 words   string"
    for word in $exmple
    do
        if (( ${#word} >= 2 ))
        then
            newstring+=$sp$word
            sp=' '
        fi
    done
    

    【讨论】:

    • 一个错误:/usr/local/sbin/testbash: line 1: This is a lovey 7 words string: command not found
    • @Dennis Williamson 你能看看你的命令吗?第一行是错误:/usr/local/sbin/testbash: line 1: This is a lovey 7 words string: command not found
    • 去掉空格即可:exmple="This is a lovey 7 words string"
    • @DocWiki:抱歉打错字了。我只是不假思索地粘贴了问题中的内容。
    • 现在可以正常使用了。也许我上次复制了一些 html 代码。非常感谢!
    【解决方案2】:

    sed 做得很好:

    example="This is a lovey 7 words string"
    echo $example | sed -e 's/ [a-zA-Z0-9]\{1\} / /g'
    

    【讨论】:

    • \{1\} 是多余的 - sed -e 's/ [a-zA-Z0-9] / /g' 工作正常。
    【解决方案3】:

    sed -e 's/ [a-zA-Z0-9] / /g' 不会删除两个或多个空格。

    这将:

    echo "This is a lovey 7 words   string" | sed 's/ [a-zA-Z0-9 ] / /g'
    

    这将删除开头或结尾的所有空格:

    echo "   This is a lovey 7 words   string  " | sed 's/ [a-zA-Z0-9 ] / /g' | sed 's/^ *\| *$//g'
    

    【讨论】:

      【解决方案4】:

      awk也可以做到:

      $ awk '{for (i=1; i<=NF; i++) s=(length($i)>2? s($i)FS : s); print s}' <<< "This is a lovey 7 words   string"
      This lovey words string 
      

      说明

      这个想法是遍历存储那些大于给定大小的字符串的所有字段。最后,打印存储的字符串。

      • for (i=1; i&lt;=NF; i++) 循环遍历所有字段。
      • s=(length($i)&gt;2? s($i)FS : s) 如果单词的长度大于 2,则将其附加到当前句子中。否则,不是。
      • print s 打印最后的字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 2017-11-03
        • 2020-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多