sed:替换一行的一部分 [英] sed: Replace part of a line
本文介绍了sed:替换一行的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用 sed 替换一行的一部分?
How can one replace a part of a line with sed?
线
DBSERVERNAME xxx
应替换为:
DBSERVERNAME yyy
值 xxx 可能会有所不同,dbservername 和值之间有两个选项卡.这个名称-值对是来自配置文件的众多名称-值对之一.
The value xxx can vary and there are two tabs between dbservername and the value. This name-value pair is one of many from a configuration file.
我尝试使用以下反向引用:
I tried with the following backreference:
echo "DBSERVERNAME xxx" | sed -rne 's/\(dbservername\)[[:blank:]]+\([[:alpha:]]+\)/\1 yyy/gip'
这导致了一个错误:'s' 命令的 RHS 上的引用无效.
and that resulted in an error: invalid reference \1 on `s' command's RHS.
表达方式有问题吗?使用 GNU sed.
Whats wrong with the expression? Using GNU sed.
推荐答案
这有效:
sed -rne 's/(dbservername)\s+\w+/\1 yyy/gip'
(当您使用 -r 选项时,您不必转义括号.)
(When you use the -r option, you don't have to escape the parens.)
解释:
-r
是扩展的正则表达式 - 对正则表达式的编写方式有所不同.-n
不打印,除非指定 -sed
否则默认打印,-e
表示它后面是一个表达式.让我们分解一下表达式:s///
是搜索替换命令,第一对之间是要匹配的正则表达式,第二对是替换,gip
,跟在搜索替换命令之后;g
表示全局,即每个匹配项而不是第一个都将在一行中被替换;i
不区分大小写;p
表示完成后打印(记住前面的-n
标志!),- 括号代表匹配部分,稍后会出现.所以
dbservername
是第一个匹配部分, \s
是空格,+
表示一次或多次(相对于*
,零次或多次)出现,\w
是一个单词,可以是任何字母、数字或下划线,\1
是 GNUsed
的特殊表达式,用于打印随附搜索中的第一个括号匹配项.
-r
is extended regular expressions - makes a difference to how the regex is written.-n
does not print unless specified -sed
prints by default otherwise,-e
means what follows it is an expression. Let's break the expression down:s///
is the command for search-replace, and what's between the first pair is the regex to match, and the second pair the replacement,gip
, which follows the search replace command;g
means global, i.e., every match instead of just the first will be replaced in a line;i
is case-insensitivity;p
means print when done (remember the-n
flag from earlier!),- The brackets represent a match part, which will come up later. So
dbservername
is the first match part, \s
is whitespace,+
means one or more (vs*
, zero or more) occurrences,\w
is a word, that is any letter, digit or underscore,\1
is a special expression for GNUsed
that prints the first bracketed match in the accompanying search.
这篇关于sed:替换一行的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文