【发布时间】:2020-01-19 13:26:42
【问题描述】:
我有以下用例,我需要使用 sed 删除一些特殊字符 (",/,\)。
sample.txt
srcs : [a.c] cflags : [abcd@ef]
srcs : ["b.c"] cflags : [ab\cd"ef]
srcs : [r/.c] cflags : [a""bcd*ef""]
srcs : [g.c] cflags : [ab/cd*ef]
需要从每行的 cflags 条目中删除 (\,",/)。预期输出:
srcs : [a.c] cflags : [abcd@ef]
srcs : ["b.c"] cflags : [abcdef]
srcs : [r/.c] cflags : [abcd*ef]
srcs : [g.c] cflags : [abcd*ef]
尝试使用正则表达式的 sed 替换机制,它在 "cflags" 和 "]" 之间搜索字符串,返回 cflags 和 ] 之间的字符串:
cat sample.txt | sed 's/cflags : \(.*\)]/\1/'
srcs : [a.c] [abcd@ef
srcs : ["b.c"] [ab\cd"ef
srcs : [r/.c] [a""bcd*ef""
srcs : [g.c] [ab/cd*ef
替换为 '' 但它会删除整个 cflags 条目:
cat sample | sed 's/cflags : \(.*\)]/''/'
srcs : [a.c]
srcs : ["b.c"]
srcs : [r/.c]
srcs : [g.c]
寻找一个可以在每一行的 cflags 和 ']' 之间找到 (\,",/) 的正则表达式,然后可以使用 sed 将其删除。
【问题讨论】: