Daeto Daeto - 4 years ago 218
Bash Question

More universal alternative to this sed command?

I have a variable called

storing directories in a dir tree:


And I have another variable called
for example that holds the names of the directories I want to remove from the dirs variable:


I am using a for loop to do that:

for d in $remove; do
dirs=$(echo "$dirs" | sed "/\b$d\b/d")

After that loop is done, what I should be left with is:


because the loop found rats.

I have tested this approach on 3 systems but it only works as expected on 2.

Is there a more universal approach that would work on all shells?

Answer Source

You are looking for something like

echo "${dirs}" | grep -Ev "rats|crabs"

When you can't store the exclusion list in the format with |, try to change it on the fly:"

echo "${dirs}" | grep -Ev $(echo "${remove}" | tr -s "\n" "|" | sed 's/|$//')

You can use the excludeFile technique without a temp file with

echo "${dirs}" | grep -vf <(echo "${remove}")

I am not sure which of there solutions will be best supported.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download