A way to print only part of directory path

Hi,

So I struggled to find a solution to the following problem:

I want to make sed print only part of multiple different paths.

So lets say we have

/path/path1/path2/logs/bla/blabla
/path/path1/path2/path3/logs/yadda/yadda/yadda

Can someone suggest a way to make sed or other utility print only the path name up to logs directory only? ie:

/path/path1/path2/logs/
/path/path1/path2/path3/logs

Thanks for the answers

By the way the solution will be implemented in a script which will run on multiple different machines, so the paths will always be different and not static.

Your desired output is inconsistent. You want the trailing /, or not?

sed "s|\(.*/logs\)[$/].*|\1|" # no
sed "s|\(.*/logs[$/]\).*|\1|" # yes

grep -o can do the same thing, probably more efficiently, but -o is possibly not portable, depending on where you plan to use it.

1 Like

Thank you very much for the quick answer. It worked like a charm.

Edit: both suggestions work, I will see which I will use when doing the deep tests.
Edit2: Yes, I know about the grep, but I cannot use grep in my script logic. The directories get extracted via lsof or pfiles.

Please help me out - why can't you use grep when you can use sed to process commands' output? Did you consider shell's "parameter expansion / suffix removal"?

That didn't work so well, if logs was the last thing in the path.

sed -nE "s#(.*/logs(/|$)).*#\1#p"
sed -nE "s#(.*/logs)(/|$).*#\1#p"

How about a totally different route:-

find / -type d -name logs

Would that do what you need?

Robin

1 Like