如何向文件添加新行并匹配prev行的缩进

y17*_*hen 1 shell scripting sed

我有:

globalweather:
    name: 'globalweather:1.0.0'
Run Code Online (Sandbox Code Playgroud)

我试过了: sed -i '' "s/^\( *\)name: '$api_name'$/&\n\1\$ref: $1/" $2

但我得到:

globalweather:
    name: 'globalweather:1.0.0'n    $ref: globalweather_1.0.0.yaml 
Run Code Online (Sandbox Code Playgroud)

我想要:

globalweather:
   $ref: globalweather_1.0.0.yaml 
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决我所缺少的问题吗?

and*_*lrc 5

您可以捕获缩进,然后使用替换来插入它:

sed 's/^\( *\)something$/&\n\1something else/'
Run Code Online (Sandbox Code Playgroud)

分解:

s/
  ^      # Start of string
  \( *\) # Capture 0 or more spaces
  something
  $      # End of string
/
  &      # Full matched string
  \1     # Captured spaces
  something else
/
Run Code Online (Sandbox Code Playgroud)

但是after命令可能会有更优雅的解决方案.