Search code examples
sedyamlyq

how to insert tab in sed command?


I have a text file in which there's a YAML formatted code. Here's the code:

trigger:
  branches:
    include:
      - develop
      - release/*
      - rapid/*
      - Sprint/*
      - Unity/*

Now, I have a bash script through which I want to add a string after this string; " - develop". Here's the point I want to maintain the spacing format. Here;s my bash file code.

 $target_string= "      - develop"
 $replacment_string="      - TerraformTest/*"
 sed -i "/$target_string/a$replacment_string" test.txt

But the result I got it this:

trigger:
  branches:
    include:
      - develop
- TerraformTest/*
      - release/*
      - rapid/*
      - Sprint/*
      - Unity/*

Is there any way, I can put tab in sed command to obtain the output like this:

trigger:
  branches:
    include:
      - develop
      - TerraformTest/*
      - release/*
      - rapid/*
      - Sprint/*
      - Unity/*

Solution

  • You can match match and grab space of search string in a capture group and use it in replacement:

    sed -E 's~^([[:blank:]]*)- develop~&\n\1- TerraformTest/*~' file
    
    trigger:
      branches:
        include:
          - develop
          - TerraformTest/*
          - release/*
          - rapid/*
          - Sprint/*
          - Unity/*
    

    Or using variables:

    target_string='- develop'
    replacment_string='- TerraformTest/*'
    
    sed -E "s~^([[:blank:]]*)$target_string~&\n\1$replacment_string~" file
    
    trigger:
      branches:
        include:
          - develop
          - TerraformTest/*
          - release/*
          - rapid/*
          - Sprint/*
          - Unity/*
    

    Breakup:

    • ^: Start
    • ([[:blank:]]*): Match 0 or more whitespaces in capture group #1
    • $target_string: Match string contained in $target_string

    Replacement:

    • &: Place whole match back
    • \n: Place a line break
    • \1: Place spaces string on next line
    • $replacment_string: Place new replacement value

    TO save changes inline use:

    sed -i.bak -E "s~^([[:blank:]]*)$target_string~&\n\1$replacment_string~" file