1

I would like to add a name in the middle of dirPath

#!/bin/bash

name='agent_name-2'
dirPath='/var/azp/1/s'

I want to insert agent_name-2 after /var/azp in dirPath, and store it in a separate variable result like this

result=/var/azp/agent_name-2/1/s
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Datadog Learning
  • 105
  • 1
  • 1
  • 5
  • 1
    What pattern do you want to find exactly? Please [edit] to clarify. BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Jun 30 '21 at 15:40
  • Updated my post – Datadog Learning Jun 30 '21 at 16:05
  • Do you want a generic solution that can insert `agent_name-2` into a path like `/var/local/6/t`, or `/var/baq/3/t`, or `/usr/azp/1/2/3/s`? If so, exactly what are the criteria to determine where to insert? Or do you just want to exactly match `/1/s`....in which case just write `result=/var/azp/"${name}"/1/s` – William Pursell Jun 30 '21 at 16:29

3 Answers3

2

If /var/azp is a hard coded string (i.e. constant), try:

name='agent_name-2'
dirPath='/var/azp/1/s'
result="/var/azp/$name${dirPath#/var/azp}"

Explanation: ${dirPath#/var/azp} removes the string /var/azp from the beginning of the string $dirPath.

Pierre François
  • 5,850
  • 1
  • 17
  • 38
0

Bash search-replace

You can use Bash's search and replace syntax ${variable//search/replace}.

prefix='/var/azp'
result=${dirPath//$prefix/$prefix\/$name}
# > /var/azp/agent_name-2/1/s

sed s

If $name doesn't contain any special characters, you could inject it into a sed search-replace:

$ sed "s|/var/azp|\0/$name|" <<< "$dirPath"
/var/azp/agent_name-2/1/s

Then for saving the result to a variable, see How do I set a variable to the output of a command in Bash?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Try this:

#!/bin/bash

name='agent_name-2'
dirPath='/var/azp/1/s'

Split dirPath by / and store it in the array dirs.

IFS=/ read -r -a dirs <<< "$dirPath"

Calculate the middle of the array.

middle=$(((${#dirs[@]}+1)/2))

Create two new arrays left and right with the left and right half of the dirs array.

left=("${dirs[@]:0:$middle}")
right=("${dirs[@]:$middle}")

Join the left and right half and put the name in between.

result="$(printf "%s/" "${left[@]}" "$name" "${right[@]}")"

Remove the trailing slash.

result=${result%/}
ceving
  • 21,900
  • 13
  • 104
  • 178