如何使用sed更新文件中指定节之后的某些文本的第一次出现

时间:2016-02-22 19:55:52

标签: bash sed

我有一个包含内容的文件:

#Section1
port=3000
port=3000

#Section2
port=3000
port=3000

我想在文本“#Section2”之后将第一次出现的“port = 3000”更新为“port = 1000”。这是输出:

#Section1
port=3000
port=3000

#Section2
port=1000
port=3000

任何人都可以给我一些关于如何使用sed的提示吗?

由于

5 个答案:

答案 0 :(得分:1)

这可能适合你(GNU sed):

sed '/#Section2/,/port/{s/\(port=\).*/\11000/}' file

答案 1 :(得分:0)

您可以使用以下命令:

sed '/#Section2/{n;s/.*/port=1000/}' file

答案 2 :(得分:0)

以下表达式将在port=3000的第一次出现与以port=1000开头的下一行

之间搜索并更改所有#Section2#
sed '/^#Section2/,/^#/s/^port=3000/port=1000/'

答案 3 :(得分:0)

awk救援!

awk '/#Section2/{f=1} f&&/port/{sub(3000,1000);f=0}1' file

#Section1
port=3000
port=3000

#Section2
port=1000
port=3000

答案 4 :(得分:0)

这是awk的工作,而不是sed。只需在段落模式下使用awk,它就会替换以3000开头的段落第二行中的第一个#Section2(即空行分隔块):

$ awk 'BEGIN{RS="";ORS="\n\n";FS=OFS="\n"} /^#Section2/{sub(/3000/,"1000",$2)}1' file
#Section1
port=3000
port=3000

#Section2
port=1000
port=3000

想要在第3行改变它吗?很简单,只需将上面的$2更改为$3

$ awk 'BEGIN{RS="";ORS="\n\n";FS=OFS="\n"} /^#Section2/{sub(/3000/,"1000",$3)}1' file
#Section1
port=3000
port=3000

#Section2
port=3000
port=1000

想要根据段落编号而不是以它开头的特定字符串来更改它吗?简单,只需测试NR(目前读取的记录/段落数)为1或2:

$ awk 'BEGIN{RS="";ORS="\n\n";FS=OFS="\n"} NR==1{sub(/3000/,"1000",$2)}1' file
#Section1
port=1000
port=3000

#Section2
port=3000
port=3000

$ awk 'BEGIN{RS="";ORS="\n\n";FS=OFS="\n"} NR==2{sub(/3000/,"1000",$2)}1' file
#Section1
port=3000
port=3000

#Section2
port=1000
port=3000

想要在第127行更改吗?简单,只需将$2更改为$127 ...您就会明白 - 无论您想做什么,这一切都非常简单,因为该工具旨在处理这样的要求。以下是awk查看输入文件的方式:

$ awk 'BEGIN{RS="";ORS="\n\n";FS=OFS="\n"} { for (i=1;i<=NF;i++) printf "Record %d, Field %d of %d = <%s>\n", NR, i, NF, $i; printf "\n" }' file
Record 1, Field 1 of 3 = <#Section1>
Record 1, Field 2 of 3 = <port=3000>
Record 1, Field 3 of 3 = <port=3000>

Record 2, Field 1 of 3 = <#Section2>
Record 2, Field 2 of 3 = <port=3000>
Record 2, Field 3 of 3 = <port=3000>
相关问题