1

Where the word is repeated and only wanted to be removed from specific word location

Lets say my path is - /opt/xyz/config/config.xml 
Solution I want after using sed is: /opt/xyz/config/

how can this be obtained?

I am sick of using {sed 's/config.*//'} >> This actually removes both config words such as it looks

/opt/xyz/

I have tried using this in multiple ways

>  sed 's/config.*//'
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • `echo /opt/xyz/config/config.xml | sed 's/config\.xml//'` – Jetchisel Jan 11 '23 at 22:04
  • 1
    Only when the filename matches the previous directory? Or are you looking to always remove the filename part of the path? It's not clear what your rule is. Your `sed` fails because you are replacing the match of 'config' and anything after with nothing. – Gary_W Jan 11 '23 at 22:18
  • See: [How to remove end folder name from a path in Linux script?](https://stackoverflow.com/q/29329093/3776858) – Cyrus Jan 12 '23 at 00:25

3 Answers3

2

Maybe with something like this?

sed 's/[^/]*$//'

But if the filepath is in a shell variable then you might as well use:

mydir=${myfilepath%/*}/
Fravadona
  • 13,917
  • 1
  • 23
  • 35
1

Another potential solution, depending on your use-case, is the dirname bash function, e.g.

dirname /opt/xyz/config/config.xml
/opt/xyz/config
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
0

Using BASH parameter expansion:

p="/opt/xyz/config/config.xml"; echo "${p%/*}"
/opt/xyz/config
j_b
  • 1,975
  • 3
  • 8
  • 14