1. Got a question or need help troubleshooting? Post to the troubleshooting forum or Search the forums!

Some SED questions.

Discussion in 'Off Topic' started by WheresWaldo, Apr 23, 2019.

  1. WheresWaldo

    WheresWaldo Volunteer ( ͠° ͟ʖ ͡°)
    Staff Member

    Joined:
    Feb 18, 2015
    Messages:
    5,905
    Likes Received:
    3,593
    Need some Linux grep & sed help

    I need to read a file and search for a specific string. It the string does not exist I want to add it to the end of the file, if it does exist I want to replace the whole line I think I can do this all with a BASH script but don't exactly know how.

    Here is my example:

    Code:
    if grep -q 'firmwareupdater:' config.yaml
    then
      sed -i 's/avrdud_path:\(.*\)/avrdude_path: /usr/bin/avrdude/g config.yaml
    else
      cat config.yaml
    firmwareupdater:
      avrdude_path: /usr/bin/avrdude
    EOF
    fi
    
     
  2. WheresWaldo

    WheresWaldo Volunteer ( ͠° ͟ʖ ͡°)
    Staff Member

    Joined:
    Feb 18, 2015
    Messages:
    5,905
    Likes Received:
    3,593
    Just figured this out, the above code was just stupid and didn't work, but his code does.
    Code:
    #! /bin/bash
    
    if grep -Fq 'firmwareupdater:' config.yaml
    then
      sed -i 's|avrdud_path:.*|avrdude_path: /usr/bin/avrdude|g' config.yaml
      echo "line changed"
    else
      cat <<EOT >> config.yaml
    firmwareupdater:
      avrdude_path: /usr/bin/avrdude
    EOT
      echo "Lines added"
    fi
     
    mark tomlinson likes this.

Share This Page