Search code examples
xmldatabasebashsedmediainfo

How to make long SED script leaner and more readable as code


Here is the sed part of my script right now:

sed -i -e 's/<Codec>/<inm:Video-codec>/g;s/<Duration_String4>/<inm:D-Duration>/g;s/<Width>/<inm:Width>/g;s/<\/Codec>/<\/inm:Video-codec>/g;s/<\/Duration_String4>/<\/inm:D-Duration>/g;s/<\/Width>/<\/inm:Width>/g;s/<FileExtension>/<inm:Wrapper>/g;s/<\/FileExtension>/<\/inm:Wrapper>/g' "$1"

It's only going to get longer and longer. Is there a way to make this more readable as a piece of code? Can I have a new line for each replacement, or must I start a new sed command in order to do that?


Solution

  • First setup the sedstring in parts:

    SEDSTR='s/<Codec>/<inm:Video-codec>/g'
    SEDSTR="$SEDSTR;"'s/<Duration_String4>/<inm:D-Duration>/g'
    SEDSTR="$SEDSTR;"'s/<Width>/<inm:Width>/g'
    SEDSTR="$SEDSTR;"'s/<\/Codec>/<\/inm:Video-codec>/g'
    SEDSTR="$SEDSTR;"'s/<\/Duration_String4>/<\/inm:D-Duration>/g'
    SEDSTR="$SEDSTR;"'s/<\/Width>/<\/inm:Width>/g'
    SEDSTR="$SEDSTR;"'s/<FileExtension>/<inm:Wrapper>/g'
    SEDSTR="$SEDSTR;"'s/<\/FileExtension>/<\/inm:Wrapper>/g'
    
    sed -i -e "$SEDSTR" "$1"
    

    EDIT 1: Remark: Using shell-variables in lowercase is better. EDIT 2: Appending can be done with +=

    sedstr='s/<Codec>/<inm:Video-codec>/g'
    sedstr+=';s/<Duration_String4>/<inm:D-Duration>/g'
    sedstr+=';s/<Width>/<inm:Width>/g'
    sedstr+=';s/<\/Codec>/<\/inm:Video-codec>/g'
    sedstr+=';s/<\/Duration_String4>/<\/inm:D-Duration>/g'
    sedstr+=';s/<\/Width>/<\/inm:Width>/g'
    sedstr+=';s/<FileExtension>/<inm:Wrapper>/g'
    sedstr+=';s/<\/FileExtension>/<\/inm:Wrapper>/g'
    
    sed -i -e "${sedstr}" "$1"
    

    Your next step might be making a function that will parse a configfile.
    The configfile could have lines like

    <Codec>*<inm:Video-codec>
    </Codec>*</inm:Video-codec>
    

    (with * a nice FieldSep) and let your function take care of the backslashes.

    Or even better: tell your function is should always add an end-tag replacement, and make a config file like

    Codec/inm:Video-codec
    Duration_String4/inm:D-Duration
    Width/inm:Width
    FileExtension/inm:Wrapper