Home > Back-end >  How to replace a matching pattern inside a file to another using bash
How to replace a matching pattern inside a file to another using bash

Time:10-28

My script has many lines starting with slo. How can I replace all the strings that are starting with slo to fwd using bash commands? Any help would be appreciated. Here is a snippet of my script

template_version: 2018-03-02

resources:

  instance01:
    type: ../../../templates/nf.yaml
    properties:
      vm_name: 'slol2lvdl1'
      vm_flavour: 'dns_19te'
      image_name: 'pdns_dnsd_slo_211214121207'
      vm_az: 'az-1'
      vm_disk_root_size: '50'
      vm_disk_data_size: '50'
      network_mgmt_refs: 'int:dns_ox_slo_507:c3dns_slo_live_nc_vnns_pcg'

My requirement is to replace all slo to fwd in the above code. I have 5 files like this in the same directory.

CodePudding user response:

sed is the go-to for file content replacements with regular expressions. If every slo you want to replace is between _ characters it's fairly easy with a command like this (in GNU sed which ships with just about all linuxes):

sed -i -e 's/_slo_/_fwd_/g' files to replace

-i replaces the text inline, replacing existing file contents with updated contents.

If not all slo are within _ characters you need to worry about unintentional matches.

Be sure to make a backup of these files or if they're in a git repo work from a clean state in case you don't like the change. Using git to track the changes might make sense even if you don't currently have the files in a git repo as this will make it trivial to compare before and after.

CodePudding user response:

sed -i 's/slo/fwd/' worked! Also found many alternatives but sed was straight forward!

  • Related