I have file with names similar to the following, where v is a variable part every time:
_vvvv_id_vvvv.txt
I want to replace id every time with another variable $myvar. I'm using this regex to isolate the id part: '^_(.+)_.*\.txt$'. Now I want to replace the id captured in group match 1 with $myvar.
There will always be only one and one only matched group.
I cannot use replace since this is a plausible case:
_vvvid_id_vvvvid.txt
This is different than Replacing regex groups with sed since the part before and after the group match are variable, and I need to use a regex that will ALSO match the whole file name, not just the id part.
Example:
$regex='^_(.+)_.*\.txt$'
$myvar='bar'
$f='_12345_23_678.txt'
$result=*sed or awk magic*
echo $result # echo _12345_bar_678.txt
Thank you
No sed or awk required:
$ cat tst.sh
#!/usr/bin/env bash
regex='(_[^_]+_)[^_]+(.*)'
myvar='bar'
f='_12345_23_678.txt'
[[ $f =~ $regex ]] && result="${BASH_REMATCH[1]}${myvar}${BASH_REMATCH[2]}"
echo "$result"
$ ./tst.sh
_12345_bar_678.txt
Another suggestion:
#! /bin/bash
replace()
{
local IFS='_'
local Parts
read -a Parts <<<"$1"
Parts[2]="$2"
echo "${Parts[*]}"
}
myvar='bar'
f='_12345_23_678.txt'
result="$(replace "$f" "$myvar")"
echo "result is \"$result\""
No SED or AWK required either.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With