简体   繁体   中英

Remove Words Shorter Than 4 Characters Using Linux

I have read the following and tried to rework the command logic for what I want. But, I just haven't been able to get it right.

Delete the word whose length is less than 2 in bash

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

Remove all words bigger than 6 characters using sed

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


Please help me with a simple awk or sed command for the following:

Here is an example line of fantastic data

And get:

Here example line fantastic data

$ 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

If you store the sentence in a variable, you can iterate through it in a for loop. Then you can evaluate if each word is greater than 2 characters.

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

This is a BASH example of how to do it if you have a lot of sentences in a file which would be the most common case right?

SCRIPT (Remove words with two letters or shorter)

#!/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.

OUTPUT

$ ./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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM