【问题标题】:replace with sed command only the first occurence from a line number retrieved in a file仅用 sed 命令替换文件中检索到的行号中的第一次出现
【发布时间】:2018-05-24 01:15:51
【问题描述】:

从下面的这个 aws 配置文件中,我只想在默认部分替换 aws 区域:

[proj1]
output = json
region = aws_region

[default]
output = json
region = us-east-1

[proj2]
output = json
region = us-east-1

[proj2-frankfurt]
output = json
region = eu-central-1

从这个命令,我到达检索 [default] 部分的行号位置:

grep -n "默认" ~/.aws/config | awk -F ":" '{打印 $1}'

结果是:5(如预期)

所以,从这个输出(行号),我想用 sed 替换(唯一的)第一次出现,而不是用“eu-central-1”代替“aws_region”,例如通过执行类似的操作:

sed -i '7,/aws_region/s//eu-central-1/' ~/.aws/config

7 是我上一个命令的输出

如何在一次操作中做到这一点?

【问题讨论】:

    标签: shell sed


    【解决方案1】:

    使用 GNU sed:

    sed '/^\[default\]/,/^$/{ s/region = .*/region = foobar/ }' file
    

    输出到标准输出:

    [项目1] 输出 = json 区域 = aws_region [默认] 输出 = json 区域 = foobar [项目2] 输出 = json 地区 = us-east-1 [proj2-法兰克福] 输出 = json 地区 = eu-central-1

    如果您想“就地”编辑文件,请使用 sed 的选项 -i


    请参阅:man sedThe Stack Overflow Regular Expressions FAQ

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2023-03-14
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多