简体   繁体   English

使用sed插入一行

[英]insert a line using sed

I have an ini file looking like: 我有一个ini文件,看起来像:

...
abc = 123
def = 456
...

and I would like to change this to: 我想将其更改为:

...
abc = 123
xyz = 987
def = 456
...

I've unsuccesfully tried this: sed -i 's/abc = 123\\ndef = 456/abc = 123\\nxyz = 987\\ndef = 456/g' myfile.ini How do I fix my call to sed for this to work? 我没有成功尝试过此操作: sed -i 's/abc = 123\\ndef = 456/abc = 123\\nxyz = 987\\ndef = 456/g' myfile.ini我该如何修复对sed调用才能使其正常工作?

sed '
    /^def / {     # if this line matches the  2nd pattern
        x         # swap this line and the hold space
        /^abc / { # if this line matches the 1st pattern
                  # insert the new line
            i\
xyz = 987
        }
        x         # re-swap this line and the hold space
    }
    h             # put this line into the hold space
' file.ini

sed的另一种方法:

sed '/abc = 123/N;s/\ndef = 456/\nxyz = 987&/' myfile.ini

Sed naturally looks at only a single line, so it won't find the '\\n' character as you want it to. Sed自然只看一行,因此找不到想要的'\\n'字符。 The easiest solution is to replace all '\\n' with another temporary character like '\\f' (form feed character). 最简单的解决方案是将所有'\\n'替换为另一个临时字符,例如'\\ f'(换页符)。

Here's the hackish method I've been using. 这是我一直在使用的骇客方法。 (separated for clarity) (为清晰起见,将其分开)

cat myfile.ini |
tr '\n' '\f' |
sed -e "s/abc = 123\fdef = 456/abc = 123\fxyz = 987\fdef = 456/g" |
tr '\f' '\n'

'\\f' is the form feed character. '\\f'是换页符。 If you are on MacOS, you will need to replace all '\\f' with $(printf '\\f') in the sed statement. 如果您使用的是MacOS,则需要在sed语句中将所有'\\f'替换$(printf '\\f')

Note: I would also recommend using sed grouping syntax to make your patterns easier to read. 注意:我还建议您使用sed分组语法来使您的模式更易于阅读。

It's hard to do multiline edits with sed. 使用sed很难进行多行编辑。 You should look into perl for more complex edits. 您应该研究perl进行更复杂的编辑。

Here is a portable way of appending a line after a pattern: 这是在模式后附加行的可移植方式:

<myfile.ini sed '/abc = 123/a\
xyz = 789
'

Output: 输出:

abc = 123
xyz = 789
def = 456

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

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