如何使用sed命令在模式字符串之前添加字符串? [英] How to use sed command to add a string before a pattern string?
问题描述
我想使用sed修改名为"baz"的文件.
I want to use sed to modify my file named "baz".
当我搜索模式foo时,foo不在行的开头或结尾,我想在foo之前附加小节,我该如何使用sed呢?
When i search a pattern foo , foo is not at the beginning or end of line, i want to append bar before foo, how can i do it using sed?
Input file named baz:
blah_foo_blahblahblah
blah_foo_blahblahblah
blah_foo_blahblahblah
blah_foo_blahblahblah
Output file
blah_barfoo_blahblahblah
blah_barfoo_blahblahblah
blah_barfoo_blahblahblah
blah_barfoo_blahblahblah
推荐答案
您可以只使用以下内容:
You can just use something like:
sed 's/foo/barfoo/g' baz
(末尾的 g
表示全局,每行而不是仅出现在第一行).
(the g
at the end means global, every occurrence on each line rather than just the first).
对于任意 (而不是固定的)模式(例如 foo [0-9]
),可以使用捕获组,如下所示:
For an arbitrary (rather than fixed) pattern such as foo[0-9]
, you could use capture groups as follows:
pax$ echo 'xyz fooA abc
xyz foo5 abc
xyz fooB abc' | sed 's/\(foo[0-9]\)/bar\1/g'
xyz fooA abc
xyz barfoo5 abc
xyz fooB abc
括号捕获与模式匹配的实际文本, \ 1
使用它代替.
The parentheses capture the actual text that matched the pattern and the \1
uses it in the substitution.
您可以在此模式中使用任意复杂的模式,包括确保仅匹配完整的单词.例如,仅当模式被单词边界立即包围时,才进行更改:
You can use arbitrarily complex patterns with this one, including ensuring you match only complete words. For example, only changing the pattern if it's immediately surrounded by a word boundary:
pax$ echo 'xyz fooA abc
xyz foo5 abc foo77 qqq xfoo4 zzz
xyz fooB abc' | sed 's/\(\bfoo[0-9]\b\)/bar\1/g'
xyz fooA abc
xyz barfoo5 abc foo77 qqq xfoo4 zzz
xyz fooB abc
关于捕获组的工作方式,您可以使用括号来存储与模式匹配的文本,以供以后在替换中使用.捕获的标识符基于从左到右读取的(
字符,因此是正则表达式(为了简化起见,我省略了 \
转义字符并对其进行了一些填充):
In terms of how the capture groups work, you can use parentheses to store the text that matches a pattern for later use in the replacement. The captured identifiers are based on the (
characters reading from left to right, so the regex (I've left off the \
escape characters and padded it a bit for clarity):
( ( \S* ) ( \S* ) )
^ ^ ^ ^ ^ ^
| | | | | |
| +--2--+ +--3--+ |
+---------1---------+
应用于文本 Pax Diablo
时,将为您提供三组:
when applied to the text Pax Diablo
would give you three groups:
\1 = Pax Diablo
\2 = Pax
\3 = Diablo
如下所示:
pax$ echo 'Pax Diablo' | sed 's/\(\(\S*\) \(\S*\)\)/[\1] [\2] [\3]/'
[Pax Diablo] [Pax] [Diablo]
这篇关于如何使用sed命令在模式字符串之前添加字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!