Windows11 Git Bash下sed实现首匹配行后添加带缩进新行问题
解决Git Bash下sed仅在第一个匹配行后添加指定内容的问题
正确的sed命令
在Windows 11的Git Bash环境中,使用以下命令可仅在第一个匹配luxury_staty_villas:的行后添加带正确缩进的指定内容:
sed '0,/luxury_staty_villas:/s#&\n line_row_apartments: "/home/properties_locality/marx/platinum",#' your_file.yaml
若习惯用/作为分隔符,可转义路径中的斜杠:
sed '0,/luxury_staty_villas:/s//&\n line_row_apartments: "\/home\/properties_locality\/marx\/platinum",/' your_file.yaml
原命令的问题解析
- 匹配所有目标行:原命令未加
0,/pattern/范围限定,sed默认会处理所有匹配luxury_staty_villas:的行。添加该范围后,sed仅处理从文件开头到第一处匹配的内容,实现仅修改第一处的需求。 - 新增行格式异常(多斜杠、字符截断):原命令用
/作为sed替换分隔符,而目标路径包含大量/,导致sed将路径中的/误判为分隔符,引发解析错误。解决方式有两种:- 转义路径中所有
/(每个/前加\) - 更换替换分隔符为非
/的字符(如示例中的#),路径里的/无需转义,更不易出错。
- 转义路径中所有
示例对比
原文件内容
# 示例配置文件 property_groups: luxury_staty_villas: "/home/properties_locality/royal/gold", # 另一个可能的匹配行(仅做示例) luxury_staty_villas: "/home/properties_locality/royal/silver", other_configs: ...
错误输出(原命令导致)
# 示例配置文件 property_groups: luxury_staty_villas: "/home/properties_locality/royal/gold", \/ine_row_apartments: "/home/properties_locality/marx/platinum", # 另一个可能的匹配行(仅做示例) luxury_staty_villas: "/home/properties_locality/royal/silver", \/ine_row_apartments: "/home/properties_locality/marx/platinum", other_configs: ...
期望输出
# 示例配置文件 property_groups: luxury_staty_villas: "/home/properties_locality/royal/gold", line_row_apartments: "/home/properties_locality/marx/platinum", # 另一个可能的匹配行(仅做示例) luxury_staty_villas: "/home/properties_locality/royal/silver", other_configs: ...
内容的提问来源于stack exchange,提问作者Rafa S
相关产品推荐
相关产品推荐

