0

I am having a long list of strings (actually files names) $var looking like this

p1035sEthinylestradiol913
p1035sTAbs872
p946sCarbaryl1182

Now I wish to replace the string, which occurs between the first s and the first integer [1-9], with R. Hence the output should look like:

p1035sR913
p1035sR872
p946sR1182

I was trying something like this:

echo ${var/s*[1-9]/R}

But this of course will remove the first integer in the string after the smatch and that is not what I want. Can someone help me out here? Thanks a lot in advance!

1 Answer 1

1

To keep the matched digit you could switch from parameter expansions like ${var/s*[1-9]/R} to matching [[ string =~ pattern ]]. The matched digit could then be retrieved by BASH_REMATCH. However, you still had to do this for every entry in your list.

With sed you automatically change every line and keeping the digit is easy:

sed -E 's/s.*([0-9])/sR\1/' file

or

someCommand | sed -E 's/s.*([0-9])/sR\1/'
Sign up to request clarification or add additional context in comments.

1 Comment

It looks like in OP's case it would be echo "$var" | sed ...

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.