[英]Find and replace text containing a new line
In bash, how can I find and replace some text containing a new line? 在bash中,如何查找和替换一些包含换行符的文本?
I want to match exactly 2 lines as specified (I can't match them separately as both lines appear at different places separately & I only want to replace where both lines appear consecutively). 我想精确匹配指定的2行(我不能分别匹配它们,因为两条线分别出现在不同的位置,而我只想替换两条线连续出现的位置)。 Using sed I was able to find and replace the individual lines and new line separately, but not together!
使用sed,我能够分别找到并替换单独的行和新行,而不是一起找到!
In case if needed, below are the lines I want to find and replace (from multiple files at once!): 如果需要,下面是我要查找和替换的行(一次从多个文件中!):
} elseif ($this->aauth->is_member('Default')) { $form_data['userstat'] = $this->aauth->get_user()->id;
In general you can used sed -z
which tells sed
to use the null-character to split lines. 通常,您可以使用
sed -z
告诉sed
使用空字符来分割行。 Assume you have the file text
containing 假设您的文件
text
包含
Hello World
This is a line
line1
line2
Hello World, again
line1
line2
end
Executing sed -z -e 's/line1\\nline2/xxx/g' text
yields 执行
sed -z -e 's/line1\\nline2/xxx/g' text
产生
Hello World
This is a line
xxx
Hello World, again
xxx
end
You can add *
(that is <space><star>
) to handle inconstant white spaces. 您可以添加
*
(即<space><star>
)来处理不固定的空格。
In your specific case if you want to delete the second line you can use a block statement to advance to the next line and delete it if it matches the second line 在特定情况下,如果要删除第二行,可以使用block语句前进到下一行,如果与第二行匹配,则将其删除
sed -e '/line1/{n;/line2/d}' text
This might work for you (GNU sed): 这可能对您有用(GNU sed):
sed -i 'N;s/first line\nsecond line/replacement/;P;D' file ...
Keep a moving window of two lines in the pattern space and replace when necessary. 在模式空间中保持两行移动的窗口,并在必要时进行替换。
NB -i
option updates file(s) in place. NB
-i
选项将文件更新到位。
Also using a range and the change command: 还使用范围和change命令:
sed -i '/first line/,/second line/c\replacement1\nreplacement2\netc' file ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.