【问题标题】:Removing list of comma separated words from a sentence从句子中删除逗号分隔的单词列表
【发布时间】:2017-03-17 04:59:11
【问题描述】:

我有两个变量如下:

sentence="name string,age int,address string,dob timestamp,job string"
ignore="age int,dob timestamp"

基本上我需要遍历逗号分隔变量$ignore 并从上述变量$sentence 中删除每个单词。

执行此操作后,输出语句应如下所示:

echo $outputsentence
name string,address string,job string

我是否应该为要忽略的单词创建一个数组并遍历它并执行 sed 操作?有没有其他办法?

【问题讨论】:

标签: arrays shell unix awk sed


【解决方案1】:

使用 GNU sed:

pattern=$(sed "s/,/|/g" <<< "$ignore")
outputsentence=$(sed -r 's/('"$pattern"'),*//g' <<< "$sentence")

第一个 sed 命令将忽略列表中的所有 , 替换为交替运算符 |。

此结果用作从$sentence 中删除字符串的模式。

【讨论】:

    【解决方案2】:

    这是需要集合的情况:您想知道集合 A 的哪些成员不存在于集合 B 中。

    为此,我们有一篇漂亮的文章 Set Operations in the Unix Shell 描述了所有这些。

    如果你想检查集合的交集,说:

    $ comm -12 <(tr ',' '\n' <<< "$sentence" | sort) <(tr ',' '\n' <<< "$ignore" | sort)
    age int
    dob timestamp
    

    对于补充,使用comm -23:

    $ comm -23 <(tr ',' '\n' <<< "$sentence" | sort) <(tr ',' '\n' <<< "$ignore" | sort)
    address string
    job string
    name string
    

    注意tr ',' '\n' &lt;&lt;&lt; "$var" | sort 只是将, 分隔的字符串分割成片。那么&lt;( ) 就是process substitution。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多