0

Suppose my LD_LIBRARY_PATH is now dir_a:dir_b:dir_c:prj/foo/build:dir_d or dir_a:dir_b:dir_c:prj/foo1/build:dir_d. By using bash script, I want to examin this LD_LIBRARY_PATH and if there is a directory path containing pattern foo*/build I want to remove this foo*/build part. How can I do it?
If this *foo*/build is the last part of LD_LIBRARY_PATH, I know I can remove it by export xx=${xx%:*foo*/build} but I don't know how to do it if this *foo*/build part is surrounded by :s.

Chan Kim
  • 4,339
  • 10
  • 39
  • 84

2 Answers2

1

This should do it:

export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | sed 's/foo.*\/build//g')
Necklondon
  • 783
  • 2
  • 11
  • `sed '...' << – Charles Duffy May 24 '22 at 22:34
  • A more serious problem here -- what if there's a `:dir_e/build` at the end of the variable? Matching until `/build` isn't ideal if you can't make it non-greedy (a PCRE extension that `sed` isn't guaranteed to have available). – Charles Duffy May 24 '22 at 22:37
  • Agree. My answer is not meant to be a generic solution, just one that fits this specific question. – Necklondon May 24 '22 at 22:40
  • I guess `/` is matched by `*` in the question `foo*/build`. So `/bar` is matched by `*`. Well... useless discussion. – Necklondon May 24 '22 at 23:20
  • This also works but chose another answer just because it's more natural and contains new method for me. :). An upvote. Anyway Thanks! – Chan Kim May 25 '22 at 07:38
1
LD_LIBRARY_PATH=$( tr : $'\n' <<<$LD_LIBRARY_PATH | grep -v YOURPATTERN | paste -s -d : )

where YOURPATTERN would be a simple regex describing the component you want to be remove. Depending on its complexity, you may consider the options -E, -F or -P of course.

The tr splits the path into segments. The grep removes the unwanted ones. The paste reassembles.

user1934428
  • 15,702
  • 7
  • 33
  • 75