Wednesday, 19 July 2017

bash - Using grep or sed to substitute words not matching a pattern



I am new to the regular expression paradigm and I've encountered a problem I'm trying to solve, with no success.



Imagine a file test.txt with:




hello everyone, whatsi up
i hope my program worksa
if it doesnt... ho well!


I would like to output to another file output.txt only the words that start with a consonant and end with a vowel so it would result in:



hello whatsi
hope worksa

ho


I am using grep -o '\b[^ aeiouAEIOU]\w*[aeiouAEIOU]\b' test.txt > output.txt however, the -o flag outputs every matched string onto a new line. What should I do to get the format that I want? Another valid option would be to substitute everything that doesn't match that pattern with a blank space using sed but I failed to do it as well. Should I be using sed or awk instead?



Thanks


Answer



Following awk solution could help you in same too.



awk '{for(i=1;i<=NF;i++){if(tolower($i) ~ /^[^aeiou].*[aeiou]$/){val=val?val OFS $i:$i}};print val;val=""}'  Input_file



Output will be as follows.



hello whatsi
hope worksa
ho


Adding a non-one liner form with explanation too here.




awk '{
for(i=1;i<=NF;i++){ ##Starting a for loop here which starts from variable i value from 1 to till the value of NF(number of fields) value.
if(tolower($i) ~ /^[^aeiou].*[aeiou]$/){ ##checking here condition if a field value in lower is satisfying the regex where I am checking if a value NOT starts from vowel and it is ending with vowels.
val=val?val OFS $i:$i ##Creating a variable named val which will have value of current field value and it will concatenate its own value.
}
};
print val; ##Outside of loop, I am printing the value of variable val here, which will have all those words which are satisfying your conditions.
val="" ##Nullifying the value of variable val here.
}

' Input_file ##Mentioning the Input_file name here.

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...