I'm getting 2 arguments inside a script and I want to replace part of the string in arg1 based of the format of arg2, where DATEFORMAT
is the reserved word for the placeholder. For example:
]$ ./a.sh nir_20210401-test (1).txt nir_DATEFORMAT-file.txt
nir_20200101-test (1).txt
a.sh
looks like:
DATE="20200101"
NAME="${1}"
FORMAT="${2}"
#getting the delimiter before the DATEFORMAT
SRC_FIRST_DELIMITER="${FORMAT%%DATEFORMAT*}"
SRC_FIRST_DELIMITER="${SRC_FIRST_DELIMITER: -1}"
#getting the delimiter after the DATEFORMAT
SRC_SECOND_DELIMITER="${FORMAT##*DATEFORMAT}"
SRC_SECOND_DELIMITER="${SRC_SECOND_DELIMITER:0:1}"
#the index/place of DATEFORMAT based of the delimiter
SRC_FORMAT_DELIMITER_IDX=$(<<<"$FORMAT" awk -v RS="$SRC_FIRST_DELIMITER" -v word="DATEFORMAT" '$0 ~ word{print NR-1}')
echo "$NAME" <--- I want here to use SRC_FIRST_DELIMITER, SRC_SECOND_DELIMITER, and SRC_FORMAT_DELIMITER_IDX to replace 20210401 with 20200101
EDIT: This one is a good start, but of course this is only if the first and second delimiter are the same which is not what I want:
echo "${NAME}" | awk -F${SRC_FIRST_DELIMITER} -v OFS=${SRC_FIRST_DELIMITER} '{$'$SRC_FORMAT_DELIMITER_IDX'="20200101"; print }'