Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sed replace a part of a path with the current directory

I have a file containing a lot paths. I need to replace all those path (containing build numbers) by the current path.
In other word in my file I have like :

/build/8b7yrg_k/12/src/main/myfile

and I want (if I’m in /build/home/0/):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/build/home/0/src/main/myfile

What I’m trying is to do :

sed 's,/build/'.+'/'[0-9]+'/','$PWD',g

But the the command doesn’t find the pattern. I also tried to add \ or to remove the ‘ but I don’t manage to match the desired patterns

>Solution :

There are several issues:

  • In POSIX BRE patterns, + is treated as a literal char, not a quanitifier
  • In single quotes, variable expansion is not enabled
  • The replacement is missing a slash (even if you fix the above, the current directory will appear glued to the remaining part of your path).

You can use

sed -E 's,/build/[^/]+/[0-9]+/,'"$PWD"/',g'
sed 's,/build/[^/]*/[0-9]*/,'"$PWD"/',g'

Details:

  • /build/[^/]+/[0-9]+/ is a POSIX ERE regex (enabled with -E) that matches /build/, one or more chars other than /, then a /, one or more digits and then a / chr
  • /build/[^/]*/[0-9]*/ is a POSIX BRE pattern that does the same as above
  • "$PWD"/ – the current directory variable is inside double quotes, and the / is added to make this replacement pattern work.

See the online demo:

#!/bin/bash
s='/build/8b7yrg_k/12/src/main/myfile'
sed -E 's,/build/[^/]+/[0-9]+/,'"$PWD"/',g' <<< "$s"
sed 's,/build/[^/]*/[0-9]*/,'"$PWD"/',g' <<< "$s"

Output:

/home/3octv4/src/main/myfile
/home/3octv4/src/main/myfile
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading