简体   繁体   English

Sed替换整条生产线

[英]Sed replace entire line with replacement

I posted this question on superuser a bit ago, but I haven't gotten an answer I like. 我刚刚在超级用户上发布了这个问题 ,但我还没有得到我喜欢的答案。 Here it is, slightly modified. 在这里,稍作修改。

I was hoping for a way to make sed replace the entire line with the replacement (rather than just the match) so I could do something like this: 我希望有一种方法可以让sed用替换(而不仅仅是匹配)替换整行,所以我可以这样做:

sed -e "/$some_complex_regex_with_a_backref/\1/"

and have it only print the back-reference. 并让它只打印反向引用。

From this question , it seems like the way to do it is mess around with the regex to match the entire line, or use some other tool (like perl). 这个问题来看,似乎这样做的方法是使用正则表达式来匹配整行,或使用其他工具(如perl)。 Simply changing the regex to .*regex.* doesn't always work (as mentioned in that question). 简单地将regex更改为.*regex.*并不总是有效(如该问题中所述)。 For example: 例如:

$ echo $regex
\([:alpha:]*\)day

$ echo "$phrase"
it is Saturday tomorrow
Warm outside...

$ echo "$phrase" | sed "s/$regex/\1/"
it is Satur tomorrow
Warm outside...

$ echo "$phrase" | sed "s/.*$regex.*/\1/"

Warm outside...

$ # what I'd like to have happen
$ echo "$phrase" | [[[some command or string of commands]]]
Satur
Warm outside...

I'm looking for the most concise way to replace the entire line (not just the matching part) assuming the following: 假设以下内容,我正在寻找最简洁的方法来替换整行(而不仅仅是匹配部分):

  • The regex is in a variable, so can't be changed on a case by case basis. 正则表达式是一个变量,因此不能根据具体情况进行更改。
  • I'd like to do this without using perl or other beefier languages (sed, awk, grep, etc. are ok) 我想这样做而不使用perl或其他更强大的语言(sed,awk,grep等等都可以)
  • The solution can't remove lines that don't match the original regex (sorry grep -o doesn't cut it). 该解决方案无法删除与原始正则表达式不匹配的行(抱歉grep -o不会删除它)。

What I thought of was the following (but it's ugly, so I'd like to know if there is something better): 我想到的是以下(但它很难看,所以我想知道是否有更好的东西):

$ sentinel=XXX
$ echo "$phrase" | sed "s/$regex/$sentinel\1$sentinel/" |
> sed "s/^.*$sentinel\(.*\)$sentinel.*$/\1/"

这可能对你有用:

sed '/'"$regex"'/!b;s//\n\1\n/;s/.*\n\(.*\)\n.*/\1/' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM