Koushik Chandra Koushik Chandra - 4 months ago 15
Bash Question

reading file and then writing against a variable in the same file

I have a file where few parameter is specified like load_start_date, load_end_date etc. like below. I also have a variable in that same file called part_date.



Now my intention is to read the file (specifically read the load_start_date parameter) , deduct 1 day (i.e. for this example it will be 2016-10-02) and then convert the format as YYYYMMDD (e.g. 20161003) save save the value against the variable part_date like below.



how easily this can be achieved?


I suggest taking advantage from the fact that the strings in your file are well suited for assignment:

#!/bin/bash -
  source file.txt
  if test "$load_start_date" != ""; then
    part_date=$(date -d "$load_start_date - 1 day" "+%Y%m%d")

    sed -i -e "s/^part_date=.*/part_date=$part_date/" file.txt

The source command evaluates file.txt in the current context, i.e. creates variables $load_start_date, $load_end_date, and $part_date. This would have been a little bit unsafe, if we hadn't used subshell expression (the curly braces) which creates special scope for the block of code.

Then we simply assign the date before $load_start_date to $part_date variable, then replace corresponding line in the source file by means of sed.