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
  • 5,177
  • 12
  • 57
  • 112

2 Answers2

1

This should do it:

export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | sed 's/foo.*\/build//g')
Necklondon
  • 928
  • 4
  • 12
  • `sed '...' <<<"$LD_LIBRARY_PATH"` is typically a bit more efficient than setting up a pipeline (at least if your tmpdir is on tmpfs / otherwise in RAM), and it avoids some correctness problems `echo $variable` has. On that latter count, see [I just assigned a variable. Why does `echo $variable` show something different?](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else), and [Why is printf better than echo?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) – 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
  • 19,864
  • 7
  • 42
  • 87