2

I have this bash script

#!/bin/bash
cat $@ | while read line
do
    for word in $line
    do
        echo $word | circling-the-square
        # here's where i need to add the if statement:
        #if the word contains one of the four [!?.,],
        #then also echo that punctuation mark
    done
done

circling-the-square is a Python script based on Norvig's spelling corrector.

That script rids its input of punctuation

def words(text): return re.findall('[a-z]+', text.lower()) 

so I need bash to notice this. I guess sed or awk might be useful but I still don't know how to write that regex or put it in an if statement, so I'm asking this here.

As is, passing the file

alec@ROOROO:~/oddi-o/newton-fluxions$ cat 199
 advertisement lately publijtid by the author, the british hemisphere, or a map of a new contrivance, proper for initiating young minds in the firft rudiments of geography, and the ufe of the globes.

gives

alec@ROOROO:~/oddi-o/newton-fluxions$ ./hmmb 199
advertisement
lately
publijtid

by
the
author
the
british
hemisphere
or
a
map
of
a
new
contrivance
proper
for
initiating
young
minds
in
the
first
rudiments
of
geography
and
the
few
of
the
globes.

Which isn't perfect but still useful. FYI, I have edited the file in question to contain only \w and the punctuation [!?.,]. The file does not contain characters like : or ;, so I just need it to echo these four punctuation marks if they are included as part of a word, viz.:

alec@ROOROO:~/oddi-o/newton-fluxions/finforno$ ./hmmb 199
advertisement
lately
publijtid
by
the
author,
the
british
hemisphere,
or
a
map
of
a
new
contrivance,
proper
for
initiating
young
minds
in
the
firft
rudiments
of
geography,
and
the
ufe
of
the
globes.
  • 2
    Wouldn't it be easier to modify the Python script? – Mikel May 24 '12 at 19:44
  • 1
    Python and Perl a certainly better suited for the job. – Tim May 24 '12 at 19:56
3

Use a regex as shown below. It finds words containing one or more of your specified punctuation marks and prints out the word and the first matching punctuation mark. You can extend it as you see fit.

if [[ "$word" =~ ^.*([!?.,])+.*$ ]]
then
    echo "Found word: $word containing punctuation mark: ${BASH_REMATCH[1]}"
fi
  • works like a charm! – ixtmixilix May 25 '12 at 23:53
1

Sounds like bash regex might help. Stackoverflow discussion about the topic: https://stackoverflow.com/questions/304864/how-do-i-use-regular-expressions-in-bash-scripts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.