han5000
han5000

Reputation: 99

Replacing variable section in string

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!

Upvotes: 0

Views: 39

Answers (1)

Socowi
Socowi

Reputation: 27195

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/'

Upvotes: 1

Related Questions