My script gets this string for example:
/dir1/dir2/dir3.../importance/lib1/lib2/lib3/file
let's say I don't know how long the string until the /importance
.
I want a new variable that will keep only the /importance/lib1/lib2/lib3/file
from the full string.
I tried to use sed 's/.*importance//'
but it's giving me the path without the importance
....
Here is the command in my code:
find <main_path> -name file | sed 's/.*importance//
Sorry my friends I have just wrong about my question,
I don't need the output /importance/lib1/lib2/lib3/file
but /importance/lib1/lib2/lib3
with no /file in the output.
Can you help me?
I would use awk
:
$ echo "/dir1/dir2/dir3.../importance/lib1/lib2/lib3/file" | awk -F"/importance/" '{print FS$2}'
importance/lib1/lib2/lib3/file
Which is the same as:
$ awk -F"/importance/" '{print FS$2}' <<< "/dir1/dir2/dir3.../importance/lib1/lib2/lib3/file"
importance/lib1/lib2/lib3/file
That is, we set the field separator to /importance/
, so that the first field is what comes before it and the 2nd one is what comes after. To print /importance/
itself, we use FS
!
All together, and to save it into a variable, use:
var=$(find <main_path> -name file | awk -F"/importance/" '{print FS$2}')
I don't need the output
/importance/lib1/lib2/lib3/file
but/importance/lib1/lib2/lib3
with no /file in the output.
Then you can use something like dirname
to get the path without the name itself:
$ dirname $(awk -F"/importance/" '{print FS$2}' <<< "/dir1/dir2/dir3.../importance/lib1/lib2/lib3/file")
/importance/lib1/lib2/lib3