我想用sed语句来匹配一个regex,以包含每一行不以 "回车 "开头的内容。
我们的目标是在每一行不以 "回车 "开头的行前加上一些内容。
符号可以在行首,也可以在行前有一个或多个空格(或制表符),任何其他我需要匹配的行,甚至是有符号的行。不 在开始的时候。
这是我到目前为止的情况。
cat myfile.txt
`this line starts with backtick`
`this one does too, but there are some spaces`
!some stuff on May 14 19:52:58 2020
more stuff *(&) 243123123123
indented stuff
indented stuff
string here that is nothing special
*here is an asterisk
match `this line`
1 number one
2 number two
`ignore this one`
这是我的sed表达式(在Mac上)。
sed -e 's/^\([^[\s*`].*\)/--matched--\1/g' myfile.txt
`this line starts with backtick`
--matched-- `this one does too, but there are some spaces`
--matched--!some stuff on May 14 19:52:58 2020
--matched--more stuff *(&) 243123123123
--matched-- indented stuff
--matched-- indented stuff
string here that is nothing special
*here is an asterisk
--matched-- match `this line`
--matched-- 1 number one
--matched-- 2 number two
--matched-- `ignore this one`
编辑:清晰
最简单的方法是匹配那些你想忽略的行,然后否定匹配。 这里有一个符合POSIX标准的方法。
sed --posix '/^[[:space:]]*`/!{/^$/!s/^/--matched---/}' ./myfile.txt
$ sed --posix '/^[[:space:]]*`/!{/^$/!s/^/--matched---/}' ./myfile.txt
`this line starts with backtick`
`this one does too, but there are some spaces`
--matched---!some stuff on May 14 19:52:58 2020
--matched---more stuff *(&) 243123123123
--matched--- indented stuff
--matched--- indented stuff
--matched---string here that is nothing special
--matched---*here is an asterisk
--matched--- match `this line`
--matched--- 1 number one
--matched--- 2 number two
`ignore this one`
这可能对你有用(GNU sed)。
sed '/^\s*$\|^\s*`/!s/^/--matched--/' file
如果该行是空的(也可能只包含空格),或者第一个非空格字符是勾,不要在前面添加 --matched--
.