[英]Replace line by string or create new one if doesn't exist - sed
I want to replace 'DUMP=' line or add new line if doesn't exist within a certain block. 我想替换'DUMP ='行或如果某个块中不存在则添加新行。 When block define by from [text]
until the next [text]
, for example: 从[text]
到下一个[text]
定义块时,例如:
[name]
sometext=...
moretext=...
DUMP=
moretext2=...
[name2]
...
For replacing existing line I will do: 为了替换现有的行,我将执行以下操作:
sed -i '/^\['name'\]$/,/^\[/!b
/DUMP=/cDUMP=example' $file
I don't know if it is possible in one liner or two, but how do I add the option to add DUMP=...
if it doesn't exists in that block? 我不知道在一两个班轮中是否可行,但是如果该区块中不存在DUMP=...
我如何添加该选项呢?
Example 1: 范例1:
file1.txt
: file1.txt
:
[name]
A=text1
B=text2
DUMP=x
C=text3
[name2]
A=text12
B=text22
DUMP=x2
C=text32
sed '/^\\['name'\\]$/,/^\\[/!b /DUMP=/cDUMP=example' file1.txt
output: sed '/^\\['name'\\]$/,/^\\[/!b /DUMP=/cDUMP=example' file1.txt
输出:
[name]
A=text1
B=text2
DUMP=example
C=text3
[name2]
A=text12
B=text22
DUMP=x2
C=text32
Example 2: 范例2:
file1.txt
: file1.txt
:
[name]
A=text1
B=text2
C=text3
[name2]
A=text12
B=text22
DUMP=x2
C=text32
sed '/^\\['name'\\]$/,/^\\[/!b /DUMP=/cDUMP=example <add DUMP incase it doesn't exist>' file1.txt
output: sed '/^\\['name'\\]$/,/^\\[/!b /DUMP=/cDUMP=example <add DUMP incase it doesn't exist>' file1.txt
输出:
[name]
A=text1
B=text2
C=text3
DUMP=example
[name2]
A=text12
B=text22
DUMP=x2
C=text32
awk '/^\[/&&/]$/&&s&&!f{print " DUMP=example"; s=0}
$0 ~ "^\["blockname"]$"{s=1;f=0}
s&&/^ *DUMP=/{$0=" DUMP=example"; f=1}
1
END{if(s&&!f) print " DUMP=example"; } blockname="name" <file>
Here, we did the following: 在这里,我们执行了以下操作:
s
checks if the correct block is found 变量s
检查是否找到正确的块 f
checks if in the correct block, the entry DUMP=
is found 变量f
检查是否在正确的块中找到了条目DUMP=
/^\\[/&&/]$/&&s&&!f{print " DUMP=example"; s=0}
/^\\[/&&/]$/&&s&&!f{print " DUMP=example"; s=0}
:: If we enter a new block, and the previous block was the correct one ( s==1
) and that block did not have a DUMP=
entry ( f==0
), write one. /^\\[/&&/]$/&&s&&!f{print " DUMP=example"; s=0}
::如果输入一个新块,而上一个块是正确的块( s==1
),并且该块没有DUMP=
条目( f==0
),则写一个。 s&&/^ *DUMP=/{$0=" DUMP=example"; f=1}
s&&/^ *DUMP=/{$0=" DUMP=example"; f=1}
:: If we are in the correct block ( s==1
), and we find a DUMP=
entry, update it. s&&/^ *DUMP=/{$0=" DUMP=example"; f=1}
::如果我们在正确的块( s==1
)中,并且找到DUMP=
条目,请对其进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.