Orest Xherija
Orest Xherija

Reputation: 464

Regular expression with conditional replacement

I am trying to write a RegEx for replacing a character in a string, given that a condition is met. In particular, if the string ends in y, I would like to replace all instances of a to o and delete the final y. To illustrate what I am trying to do with examples:

Katy    --> Kot
cat     --> cat
Kakaty  --> KoKot
avidly  --> ovidl

I was using the RegEx s/\(\w*\)a\(\w*\)y$/\1o\2/g but it does not work. I was wondering how would one be able to capture the "conditional" nature of this task with a RegEx.

Your help is always most appreciated.

Upvotes: 2

Views: 1519

Answers (3)

glenn jackman
glenn jackman

Reputation: 247042

You could use some sed spaghetti code, but please don't

sed '
    s/y$//     ; # try to replace trailing y
    ta         ; # if successful, goto a
    bb         ; # otherwise, goto b
    :a
    y/a/o/     ; # replace a with o
    :b
'

Upvotes: 1

Cyrus
Cyrus

Reputation: 88776

With GNU sed:

If a line ends with y (/y$/), replace every a with o and replace trailing y with nothing (s/y$//).

sed '/y$/{y/a/o/;s/y$//}' file

Output:

Kot
cat
Kokot
ovidl

Upvotes: 4

anubhava
anubhava

Reputation: 785641

You may use awk:

Input:

cat file

Katy
cat
KaKaty
avidly

Command:

awk '/y$/{gsub(/a/, "o"); sub(/.$/, "")} 1' file

Kot
cat
KoKot
ovidl

Upvotes: 3

Related Questions