Search code examples
bashawkseddate-format

How to replace a string into date format MM/DD/YYY argument from an user input by using awk script within bash script?


Couldn't figure how to replace a string from text file into date format MM/DD/YYYY from user input as an argument. For example:

$ ./test.bash text.txt 09/16/2020
The date was 09/16/2020

text.txt

The date was [[date_arg]]

$cat test.bash

#!/bin/bash

text=$filename.txt
date=$(date +$m/$d/$Y)

if [[ $# -eq 1 ]]; then
text=$1
elif [[ $# -eq 2 ]]; then
text=$1
date=$2

awk -f f.awk $text $date

fi

I was using a sed code within awk script to see if it works with it, but it didn't works out.

f.awk

BEGIN {
RS=""
}
NR==FNR {
t=$0
next
}
{
sub(/\[\[date_arg\]\]/,$(date+ $m/$d/$Y),t)
print t
}

Solution

  • Going by OP's attempt here, could you please try following. cat script.bash only there to show script's content actual script starts from #! line.

    cat script.bash
    #!/bin/bash
    
    if [[ $# -eq 2 ]]
    then
        file=$1
        myDate=$2
    elif [[ $# -lt 2 ]]
    then
        echo "Please pass 2 arguments in script, where 1st should be Input_file name and 2nd should be date in mm-dd-yyyy format. Exiting from script now.."
        exit 1;
    fi
    
    awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file" 
    

    In case you want to save output into provided file name itself(inplace editing) then change above awk command to awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file" > temp && mv temp "$file", better to test above first and then look for inplace editing.