linux - bash中删除长度小于2的单词

标签 linux bash command-line

我在 CentOS 5.5 上使用 bash。我有一个由空格分隔的字符串,该字符串只包含字母和数字,并且这个字符串可能有额外的空格,例如 "words""之间有超过 1 个空格字符串":

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

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

所以字符串变成:

"This is lovey words string"

最佳答案

编辑(基于 ennuikiller 的 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

关于linux - bash中删除长度小于2的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4417663/

相关文章:

Linux 启动 init.d 文件总是失败并跟随 bash,这是怎么回事?

linux - 在 unix/linux 命令行中定义函数(例如 BASH)

c++ - 是否有用于在 C++ 中编写 linux 命令行实用程序的标准模式?

windows - 如何从 Emacs 中运行 Cygwin Bash Shell?

c - 如何在 gstreamer 命令行的接收器定义的引号内转义引号

.net - 如何在 Linux 环境下运行 .net 应用程序?

php - MySQL 数据库时常需要刷新表。我可以编写一些脚本来解决这个问题吗?

c++ - 在应用程序中使用 Rsync 和增量传输算法

linux - Bash - 定位脚本并使用选项执行

java - 使用 Java 从 Linux 获取所有组