[英]Bash string manipulation with/without whitespaces
Consider having a String in bash holding a list of items: 考虑在bash中使用String来保存项目列表:
# BLUBB="item foobar blubb bar"
Further consider having an exclude list of items: 进一步考虑有一个排除项目清单:
# EXCLUDE="item bar blubb"
What would be the easiest way to resolve this to a list holding BLUBB w/o EXCLUDE. 解决此问题的最简单方法是将列表保存为不包含BLUBB的列表。 My first approach was:
我的第一种方法是:
# for i in $EXCLUDE; do BLUBB=${BLUBB//$i/}; done
But this additionally removes the bar
from foobar
. 但这还从
foobar
删除了bar
。 So it seems, one has to look for whitespace or nothing before and after the $i
. 如此看来,在
$i
前后都必须寻找空白或什么也没有。 How is the syntax for this? 语法如何?
Something like this can be done: 可以这样做:
#/bin/bash
BLUBB="item foobar blubb bar"
EXCLUDE="item bar blubb"
for word in ${BLUBB} ${EXCLUDE} ${EXCLUDE}; do
echo ${word}
done | sort | uniq -u
I'd do this in bash with an associative array: 我会在bash中使用关联数组进行此操作:
$ BLUBB="item foobar blubb bar"
$ EXCLUDE="item bar blubb"
$ declare -A h
$ for word in $BLUBB; do h[$word]=1; done
$ declare -p h
declare -A h='([blubb]="1" [bar]="1" [foobar]="1" [item]="1" )'
$ for word in $EXCLUDE; do unset "h[$word]"; done
$ declare -p h
declare -A h='([foobar]="1" )'
$ words="${!h[*]}"
$ echo "$words"
foobar
If any of the "words" in BLUBB or EXCLUDE contain whitespace, you have to use indexed arrays to hold them: 如果BLUBB或EXCLUDE中的任何“单词”包含空格,则必须使用索引数组来保存它们:
$ BLUBB=(item foobar blubb bar "word with spaces")
$ EXCLUDE=(item bar blubb with)
$ declare -A h
$ for elem in "${BLUBB[@]}"; do h["$elem"]=1; done
$ for elem in "${EXCLUDE[@]}"; do unset "h[$elem]"; done
$ declare -p h
declare -A h='(["word with spaces"]="1" [foobar]="1" )'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.