Home > front end >  Remove a matching string after a specific string a file using shell command
Remove a matching string after a specific string a file using shell command

Time:01-25

I have below content in my file abcd.yml with below indentation:

buildConfig:
  env:
    credentials:       # want to remove this from file
      - id: TEST_ID    # want to remove this from file
        user: username # want to remove this from file 
        password: password  # want to remove this from file
scan:
    credentials:
      - id: scan_id
        user: username
        password: password 

Tried the below :

sed -i '/credentials:/d'  abcd.yml
sed -i '/- id: TEST_ID/d'  abcd.yml
sed -i '/user: username/d'  abcd.yml
sed -i '/password: password/d'  abcd.yml

But it is removing all the occurrence of the above strings from file which I don't want.

Expected Output:

buildConfig:
  env:
scan:
    credentials:
      - id: scan_id
        user: username
        password: password 

I need to do this for 1000 files .Hence a script is required to do it .The file is in .yml format.

CodePudding user response:

Use a yaml parser like yq for this:

$ yq eval 'del(.buildConfig.env.credentials)' abcd.yml > newfile.yml
$ cat newfile.yml

buildConfig:
  env: {}
scan:
  credentials:
    - id: scan_id
      user: username
      password: password

tested with version v4.30.8

  • Related