sed查找并替换由[]包围的字符串输出到文件

有以下文件

"SCAN_IN[0]" : input;

想要使用sed查找并替换为scan_o

我正在使用以下命令

sed  's/SCAN_IN[]0[]/scan_0/' fileA > fileB

这就是我得到的

"scan_00]" : input;

我想要

"scan_0" : input;
评论
  • 喵oo
    喵oo 回复

    The SCAN_IN[]0[] pattern matches SCAN_IN first and then []0[] matches one char: either ], or 0, or [ (due to "smart placement" when the unescaped ] located right after the opening bracket expression [ (or [^ is it is a negated bracket expression) is treated as a literal ] and not the closing bracket expression char).

    In your string, SCAN_IN[]0[] matches SCAN_IN[ and thus the result of the replacement is scan_00]" : input;.

    您可以使用

    sed 's/SCAN_IN\[0]/scan_0/' fileA > fileB
    

    See the online sed demo:

    s='"SCAN_IN[0]" : input;'
    sed 's/SCAN_IN\[0]/scan_0/'  <<< "$s"
    # => "scan_0" : input;