Shell 仅用sed命令替换文件中检索到的行号中的第一次出现
在下面的aws配置文件中,我只想替换默认部分中的aws区域:Shell 仅用sed命令替换文件中检索到的行号中的第一次出现,shell,sed,Shell,Sed,在下面的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“
[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“default”~/.aws/config | awk-F:“{print$1}”
结果是:5(如预期)
因此,从这个输出(行号),我想用sed替换(唯一的)第一次出现,而不是用“eu-central-1”替换“aws_region”,例如,通过这样做:
sed-i'7,/aws_region/s//eu-central-1/'~/.aws/config
其中7是上一个命令的输出
如何在一次操作中完成此操作?使用GNU时:
sed '/^\[default\]/,/^$/{ s/region = .*/region = foobar/ }' file
输出到标准输出:
[proj1]
output = json
region = aws_region
[default]
output = json
region = foobar
[proj2]
output = json
region = us-east-1
[proj2-frankfurt]
output = json
region = eu-central-1
[proj1]
输出=json
区域=aws_区域
[默认值]
输出=json
区域=foobar
[项目2]
输出=json
地区=美国东部-1
[法兰克福项目2]
输出=json
地区=欧盟-中部-1
如果要“就地”编辑文件,请使用sed的选项-i
请参阅:
man sed
和使用GNU sed的:
sed '/^\[default\]/,/^$/{ s/region = .*/region = foobar/ }' file
输出到标准输出:
[proj1]
output = json
region = aws_region
[default]
output = json
region = foobar
[proj2]
output = json
region = us-east-1
[proj2-frankfurt]
output = json
region = eu-central-1
[proj1]
输出=json
区域=aws_区域
[默认值]
输出=json
区域=foobar
[项目2]
输出=json
地区=美国东部-1
[法兰克福项目2]
输出=json
地区=欧盟-中部-1
如果要“就地”编辑文件,请使用sed的选项-i
请参阅:
man sed
和