2

I want to replace '_v' with a whitespace and the last dot . into a dash "-". I tried using

sed 's/_v/ /' and tr '_v' ' '

Original Text

src-env-package_v1.0.1.18

output

src-en -package 1.0.1.18

Expected Output

src-env-package 1.0.1-18
2
  • 1
    This is not "a specific character", and thus tr is not a suitable tool for this. It seems you are seeking to replace a specific sequence of characters. Commented Aug 15, 2022 at 7:37
  • _v is a string, not a character. _ is a character, as is v. Commented Aug 15, 2022 at 19:11

2 Answers 2

2

This might work for you (GNU sed):

sed -E 's/(.*)_v(.*)\./\1 \2-/' file

Use the greed of the .* regexp to find the last occurrence of _v and likewise . and substitute a space for the former and a - for the latter.

If one of the conditions may occur but not necessarily both, use:

sed -E 's/(.*)_v/\1 /;s/(.*)\./\1-/' file
Sign up to request clarification or add additional context in comments.

Comments

1

With your shown samples please try following sed code. Using sed's capability to store matched regex values into temp buffer(called capturing groups) here. Also using -E option here to enable ERE(extended regular expressions) for handling regex in better way.

Here is the Online demo for used regex.

sed -E 's/^(src-env-package)_v([0-9]+\..*)\.([0-9]+)$/\1 \2-\3/' Input_file

OR if its a variable value on which you want to run sed command then use following:

var="src-env-package_v1.0.1.18"
sed -E 's/^(src-env-package)_v([0-9]+\..*)\.([0-9]+)$/\1 \2-\3/' <<<"$var"

src-env-package 1.0.1-18


Bonus solution: Adding a perl one-liner solution here, using capturing groups concept(as explained above) in perl and getting the values as per requirement.

perl -pe 's/^(src-env-package)_v((?:[0-9]+\.){1,}[0-9]+)\.([0-9]+)$/\1 \2-\3/'  Input_file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.