0

I have this:

echo "walking ringer talking"

How do I use sed to achieve the following output?

walked ringer talked

I've tried several ways, but can't get it to work. The following commands are what I've tried.

echo "walking ringer talking" | sed 's/ing/ed/g'

This outputs walked reder talked.

echo "walking ringer talking" | sed 's/ing$/ed/g' 

This outputs walking ringer talked.

echo "walking ringer talking" | sed 's/^ing/ed/g;s/ing$/ed/g' 

This outputs walking ringer talked.

I'm trying to get this done in a bash script.

migrated from stackoverflow.com Oct 23 '16 at 12:35

This question came from our site for professional and enthusiast programmers.

0

add space 's/ing /ed /g; in your third test;

#echo "walking ringer talking" | sed 's/^ing/ed/g;s/ing$/ed/g' 
echo "walking ringer talking" | sed 's/ing /ed /g;s/ing$/ed/g'

eg:

user@host:/tmp/test$ echo "walking ringer talking" | sed 's/ing /ed/g;s/ing$/ed/g' 
walked ringer talked
2

To match either a space or newline at the end of the pattern, you can use:

sed -E 's/ing( |$)/ed\1/g'
1

Awk will split the string in three pieces and apply substitution to the desired elements. Then print $0 will return the entire (new) string.

echo $s | awk 'BEGIN{a[1]=a[3]}{for(x in a)gsub("ing","ed",$x); print $0 }'
0

You can use an "end of word" marker:

$ echo "walking ringer talking" | sed 's/ing\>/ed/g'
walked ringer talked

\> matches where you have word characters on the left and non-word characters on the right.

Or, less specific, with a word boundary:

$ echo "walking ringer talking" | sed 's/ing\b/ed/g'
walked ringer talked

\b matches any word boundary, but if it follows word characters, it's equivalent to \>.

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.