【问题标题】:how to use array in sed shell command?如何在 sed shell 命令中使用数组?
【发布时间】:2016-12-01 20:11:43
【问题描述】:

我正在尝试列出姓名:

list = a, b, c, d, e
sed "/$list/d" output_file.txt

这样包含这些变量 a、b、c、d、e 的行将从 output_file 中排除

请大家帮忙

【问题讨论】:

    标签: linux bash shell command-line sed


    【解决方案1】:

    使用 GNU grep:

    list=(a b c d e)
    (IFS="|"; grep -vE "(${list[*]})" file)
    

    或使用 GNU sed:

    list=(a b c d e)
    (IFS="|"; sed -E "/(${list[*]})/d" file)
    

    【讨论】:

    • 当我运行脚本时,终端上显示的输出看起来是正确的,但是当我打开我用我的代码单独生成的文件时,它仍然不排除列表跨度>
    • 试试这个:list=(a b c d e); (IFS="|"; grep -vE "(${list[*]})" input_file > output_file)
    【解决方案2】:

    您可以使用 BASH 数组生成带有管道的正则表达式(交替):

    list=(a b c d e) # original array
    
    printf -v re "%s|" "${list[@]}" # genera a regex delimited by |
    
    sed -E "/${re%|}/d" file # use sed on this regex
    

    【讨论】:

    • 要为sed 保存更改,请使用:sed -E -i.bak "/${re%|}/d" file
    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2017-03-23
    • 2013-12-07
    • 2014-08-03
    • 1970-01-01
    相关资源
    最近更新 更多