Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, replace group match with other variable

Tags:

linux

bash

sed

awk

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

like image 452
yhu420 Avatar asked Nov 06 '25 23:11

yhu420


2 Answers

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
like image 60
Ed Morton Avatar answered Nov 09 '25 21:11

Ed Morton


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.