使用Linux删除短于4个字符的单词

时间:2017-10-10 19:07:14

标签: linux bash unix awk sed

我已经阅读了以下内容并尝试为我想要的内容重新编写命令逻辑。但是,我只是无法做到正确。

Delete the word whose length is less than 2 in bash

尝试:echo $example | sed -e 's/ [a-zA-Z0-9]\{4\} / /g'

Remove all words bigger than 6 characters using sed

尝试:sed -e s'/[A-Za-z]\{,4\}//g'

请使用简单的awksed命令帮助我:

Here is an example line of fantastic data

得到:

Here example line fantastic data

3 个答案:

答案 0 :(得分:1)

$ echo Here is an example line of fantastic data | sed -E 's/\b\(\w\)\{,3\}\b\s*//g'
Here is an example line of fantastic data

答案 1 :(得分:0)

如果将句子存储在变量中,则可以在for循环中迭代它。然后,您可以评估每个单词是否大于2个字符。

sentence="Here is an example line of fantastic data";
for word in $sentence; do
    if [ ${#word} -gt 2]; then
        echo -n $word;
        echo -n " ";
    fi
done

答案 2 :(得分:0)

这是一个BASH示例,说明如果文件中有很多句子,这是最常见的情况吗?

SCRIPT(删除两个字母或更短的单词)

#!/bin/bash

while read line
do

    echo "$line" | sed -E 's/\b\w{1,2}\b//g' 

done < <( cat sentences.txt )

INPUT

$  cat sentences.txt
Edgar Allan Poe (January 19, 1809 to October 7, 1849) was an
American writer, poet, critic and editor best known for evocative
short stories and poems that captured the imagination and interest
of readers around the world. His imaginative storytelling and tales
of mystery and horror gave birth to the modern detective story.

Many of Poe’s works, including “The Tell-Tale Heart” and
“The Fall of the House of Usher,” became literary classics. Some
aspects of Poe’s life, like his literature, is shrouded in mystery,
and the lines between fact and fiction have been blurred substantially
since his death.

输出

$ ./grep_tests.sh
Edgar Allan Poe (January , 1809  October , 1849) was
American writer, poet, critic and editor best known for evocative
short stories and poems that captured the imagination and interest
 readers around the world. His imaginative storytelling and tales
 mystery and horror gave birth  the modern detective story.

Many  Poe’ works, including “The Tell-Tale Heart” and
“The Fall  the House  Usher,” became literary classics. Some
aspects  Poe’ life, like his literature,  shrouded  mystery,
and the lines between fact and fiction have been blurred substantially
since his death.