[英]sed - append to next line using command line
I wish to append " dddd" to the next line whenever I encounter "=" in a textfile. 每当我在文本文件中遇到“=”时,我希望将“dddd”附加到下一行。
This command 这个命令
sed -i '/=/s|$| dddd|' *.krn
is close to what I am looking for as it appends to the current line where "=" is. 接近我正在寻找的东西,因为它附加到当前行“=”。 How can I append to the next line instead? 我怎样才能附加到下一行呢?
Use append, see here: 使用追加,见这里:
Eg: 例如:
$ echo $'abc\ndef\ne=f\nqqq'
abc
def
e=f
qqq
$ echo $'abc\ndef\ne=f\nqqq'|sed '/=/adddd'
abc
def
e=f
dddd
qqq
Edited to clarify as per comment from @je4d- if you want to append to what is present in the next line, you can use this: 编辑根据@ je4d的评论澄清如果你想附加到下一行中的内容,你可以使用:
$ echo $'abc\ndef\ne=f\nqqq\nyyy'
abc
def
e=f
qqq
yyy
$ echo $'abc\ndef\ne=f\nqqq\nyyy'|sed '/=/{n;s/$/ dddd/}'
abc
def
e=f
qqq dddd
yyy
See here for a great sed cheatsheet for more info if you want: 如果您需要,请参阅此处获取更多信息的sed cheatsheet:
So to reiterate the question, when you match on one line, you want to append a string to the next line---a line that already exists, rather than adding a new line after it with the new data. 因此,要重申这个问题,当您在一行上匹配时,您希望将一个字符串附加到下一行---已存在的行,而不是在其后面添加新行与新数据。
I think this will work for you: 我认为这对你有用:
sed '/=/ { N; s/$/ ddd/ }'
Say you have a file like: 假设您有一个类似的文件:
=
hello
world
=
foo
bar
=
Then processing this command on it will yield: 然后在其上处理此命令将产生:
=
hello ddd
world
=
foo ddd
bar
=
The trick here is using the N
command first. 这里的诀窍是首先使用N
命令。 This reads in the "next" line of input. 这将读入“下一行”输入。 Commands following it will be applied to the next line. 后面的命令将应用于下一行。
I'm not a sed guru, but I can do what you want with awk: 我不是sed guru,但我可以用awk做你想做的事:
'{PREV=MATCH; MATCH="no"}
/=/{MATCH="yes"}
PREV=="yes"{print $0 " dddd"}
PREV!="yes"{print}'
Demo: 演示:
$ echo -e 'foo\nba=r\nfoo\n=bar\nfoo\nfoo\nb=ar\nx'
foo
ba=r
foo
=bar
foo
foo
b=ar
x
$ echo -e 'foo\nba=r\nfoo\n=bar\nfoo\nfoo\nb=ar\nx' | awk '{APPEND=LAST; LAST="no"} /=/{LAST="yes"} APPEND=="yes"{print $0 " dddd"} APPEND!="yes"{print}'
foo
ba=r
foo dddd
=bar
foo dddd
foo
b=ar
x dddd
This might work for you: 这可能对你有用:
echo -e "=\nx " | sed '/=/{$q;N;s/$/dddd/}'
=
x dddd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.