'sed'替换最后一个模式并删除其他模式 [英] 'sed' replace last patern and delete others pattern

查看:52
本文介绍了'sed'替换最后一个模式并删除其他模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想用文件中的"ens_delay"替换最后一个字符串"delay",并删除最后一个字符串之前的其他字符串:

I want to replace only the last string "delay" by "ens_delay" in my file and delete the others one before the last one:

输入文件:

alpha_notify_teta=''
alpha_notify_check='YES'
text='CRDS'
delay=''
delay=''
delay=''
textfileooooop=''
alpha_enable='YES'
alpha_hostnames=''
alpha_orange='YES'
alpha_orange_interval='300'
alpha_notification_level='ALL'
expression='YES'
delay='9'
textfileooooop=''
alpha_enable='YES'
alpha_hostnames=''

输出文件:(期望值)

alpha_notify_teta=''
alpha_notify_check='YES'
text='CRDS'

textfileooooop=''
alpha_enable='YES'
alpha_hostnames=''
alpha_orange='YES'
alpha_orange_interval='300'
alpha_notification_level='ALL'
expression='YES'
ens_delay='9'
textfileooooop=''
alpha_enable='YES'
alpha_hostnames=''

这是我的第一个命令,但是它不起作用,因为只有在我延迟到最后一行时它才起作用.

Here my first command but it doesn't work because it will work only if I have delay as last line.

sed -e '$,/delay/ s/delay/ens_delay/'

我的第二个命令将删除所有包含"delay"的行,甚至"ens_delay"也将被删除.

My second command will delete all lines contain "delay", even "ens_delay" will be deleted.

sed -i '/delay/d'

谢谢

推荐答案

这可能对您有用(GNU sed):

This might work for you (GNU sed):

sed '/^delay=/,$!b;/^delay=/!H;//{x;s/^[^\n]*\n\?//;/./p;x;h};$!d;x;s/^/ens_/' file

delay = 开始的第一行之前的行应正常打印.否则,将以 delay = 开头的行存储在保留空间中,并且将不以 delay = 开头的后续行附加到该行.如果保留空间已经包含这些行,则删除第一行,并在保留空间之前用当前行替换剩余的行.在文件末尾,对保留空间的第一行进行了修改,以在字符串 ens _ 之前加上前缀,然后打印整个保留空间.

Lines before the first line beginning delay= should be printed as normal. Otherwise, a line beginning delay= is stored in the hold space and subsequent lines that do not begin delay= are appended to it. Should the hold space already contain such lines, the first line is deleted and the remaining lines printed before the hold space is replaced by the current line. At the end of the file, the first line of the hold space is amended to prepend the string ens_ and then the whole of the hold space is printed.

这篇关于'sed'替换最后一个模式并删除其他模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆