Jay Taylor's notes
back to listing indexReplace Last Occurrence of Substring in String (bash)
[web search]- Home
-
- Public
- Stack Overflow
- Tags
- Users
- Jobs
-
From the bash software manual:
${parameter/pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string.
... If pattern begins with ‘%
’, it must match at the end of the expanded value of parameter.
And so I've tried:
local new_name=${file/%old/new}
Where string is an absolute file path (/abc/defg/hij
and old
and new
are variable strings.
However this seems to be trying to match the literal %sb1
.
What is the syntax for this?
Expected Output:
Given
old=sb1
new=sb2
Then
/foo/sb1/foo/bar/sb1
should become /foo/sb1/foo/bar/sb2
/foo/foosb1other/foo/bar/foosb1bar
should become /foo/foosb1other/foo/bar/foosb2bar
Using only shell-builtin parameter expansion:
src=sb1; dest=sb2
old=/foo/foosb1other/foo/bar/foosb1bar
if [[ $old = *"$src"* ]]; then
prefix=${old%"$src"*} # Extract content before the last instance
suffix=${old#"$prefix"} # Extract content *after* our prefix
new=${prefix}${suffix/"$src"/"$dest"} # Append unmodified prefix w/ suffix w/ replacement
else
new=$old
fi
declare -p new >&2
...properly emits:
declare -- new="/foo/foosb1other/foo/bar/foosb2bar"
Your Answer
Not the answer you're looking for? Browse other questions tagged bash shell pattern-matching substring variable-expansion or ask your own question.
asked |
10 months ago |
viewed |
497 times |
active |
Related
Hot Network Questions
-
Older movie/show about humans on derelict alien warship which refuels by passing through a star
-
Suing a Police Officer Instead of the Police Department
-
`microtype`: Set Minimum Width of a Space
-
How do I check if a string is entirely made of the same substring?
-
Philosophical question on logisitic regression: why isn't the optimal threshold value trained?
-
Why must Chinese maps be obfuscated?
-
Map material from china not allowed to leave the country
-
How to not starve gigantic beasts
-
Obeylines and \gappto from etoolbox
-
A faster way to compute the largest prime factor
-
Does Mathematica have an implementation of the Poisson binomial distribution?
-
How to avoid introduction cliches
-
What is this word supposed to be?
site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required. rev 2019.4.25.33441