Daeto Daeto - 4 years ago 218
Bash Question

More universal alternative to this sed command?

I have a variable called

$dirs
storing directories in a dir tree:

root/animals/rats/mice
root/animals/cats


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

rats
crabs


I am using a for loop to do that:

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


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

root/animals/cats


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