Skip to main content

Delete specific pattern in a word from a Text file [Resolved]

I have the following lines in my file:

demo-ns,demoapp-v1-v000,2733202e0e44c0c8f49a220e5596113ee35e2566
demo-ns,demoapp-v2-v001,3b3f0592b933add32f10b7e1a7535837009a4c64

I want to remove the characters -v000 and -v001. The pattern is v[0-9][0-9][0-9].

I am expecting the following output:

demo-ns,demoapp-v1,2733202e0e44c0c8f49a220e5596113ee35e2566
demo-ns,demoapp-v2,3b3f0592b933add32f10b7e1a7535837009a4c64

How can I achieve this?


Question Credit: SShetty
Question Reference
Asked October 9, 2019
Posted Under: Unix Linux
11 views
3 Answers

sed -e 's/-v[0-9][0-9][0-9],/,/'

The added comma provides a little bit of context to guard against replacing too aggressively.


credit: AlexP
Answered October 9, 2019

With GNU sed:

sed -E 's/-v[0-9]{3}//' file

credit: guillermo chamorro
Answered October 9, 2019

With awk:

awk 'BEGIN{ OFS=FS="," } { sub(/-v[0-9]*$/,"",$2); print }' file

Set the input field separator FS and output field separator OFS to a comma.
Then substitute regex pattern -v[0-9]*$ on the second comma separated field $2 with an empty string and print the line.


credit: Freddy
Answered October 9, 2019
Your Answer