-1

I'm trying to write a Bash script that will read a text file and pull out every word that is followed by a comma on a new line. I tried using grep but it prints the whole line that has a comma in it, and I have had the same trouble with awk. How to set up this script?

For example if the text file contained a list of animals, like so: " The Veterinary clinic treats the following animals: dogs, cats, and birds" the script would display:

dogs, cats,

  • 3
    Did you read the man pages for your system's version of grep? does it have a -o or --only-matching option? – steeldriver Feb 16 '16 at 16:59
  • Yes I did, and I tried it and it only prints the comma. – user52470 Feb 16 '16 at 17:05
  • 1
    So... your expression is only matching the comma: you need to make it match a sequence of word characters followed by a comma – steeldriver Feb 16 '16 at 17:10
  • I'm not quite sure how to go about doing that, I tried grep -o '[:alpha:],' and it outputs just the last letter and the comma, but only for four lines. When I did grep -o ',' there were 92 commas, so I am very confused. – user52470 Feb 16 '16 at 17:30
  • 1
    [:alpha:] means any single character from the set :,a, ... etc. - to match a character from the POSIX class [:alpha:] you will need [[:alpha:]]. You probably also want to match a non-empty sequence of such characters so look at the + and/or {n,m} modifiers. – steeldriver Feb 16 '16 at 17:40
1
sed -e 's/\([[:alpha:]]*,\)/\n\1\n/g' | grep ,

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.