Search code examples
shellsedvariable-assignment

How to alter a variable with a shell script using sed


I am attempting to alter the values in a .dat file for a model I am running. The issue is that the code cannot simply be changed with the sed -i 's/old_text/new_text/'

The .dat file I am attempting to change looks like

0.000E-00          !Argon
7.956E-03          !Methane
0.000E-00          !Ethane
1.945E-03          !Carbon Dioxide
9.901E-01          !Nitrogen
1.000E-40          !Oxygen
0.000E-00          !Hydrogen
0.000E-00          !Nitrogen Dioxide
22                 !Tropopause layer

I am attempting to alter the values for methane, nitrogen, and carbon dioxide, however I cannot simply tell it to replace '7.965E-03 !Methane' because after the first time I run the shell script, that value will change.

I have attempted to replace !Methane with $'variable name' !Methane, but that does not solve the issue of removing the number, nor will it work after the first time I compile the script.

The current script is

#file=atmos-master-copy1/CLIMA/IO/mixing_ratios.dat                                                                                        
#sed -i 's/Methane.*/'$muCH4_1'    !Methane/' $file

But I dont know how to make it start by altering the contents at the beginning of the file.


Solution

  • If you want to replace the value for !Methane with the value held by the variable $muCH4_1, then:

    sed -Ei 's/^\S+\s+(!Methane)$/'"$muCH4_1"' \1/' "$file"
    
    • ^ - Start of line anchor
    • \S+ - One or more non-whitespace characters
    • \s+ - One or more whitespace characters
    • (!Methane) - Capture !Methane into capture group 1
    • $ - End of line anchor

    Substitute with

    • '"$muCH4_1"' - The value held by the variable muCH4_1
    • - A literal space
    • \1 - !Methane from capture group 1

    Note: For the second column to line up just like in the original file, muCH4_1 must be padded with spaces to the right. If that's what you want, you can use printf to do the padding:

    sed -Ei 's/^\S+\s+(!Methane)$/'"$(printf "%-18s" "$muCH4_1")"' \1/' "$file"