-1

I got a text file a.txt like that:

start_date:{start_date};end_date:{end_date}

I want to replace {start_date} and {end_date} in shell script.

#!/bin/bash
START_DATE="2021-06-01"
END_DATE="2021-06-02"
awk '{gsub(/{start_date}/, '$START_DATE'); gsub(/{end_date}/, '$END_DATE');print $0 }' a.txt

I want to get something like:

start_date:2021-06-01,end_date:2021-06-02

But acutally I got:

start_date:start_date:2014;end_date:2013

It seems that the variable START_DATE and END_DATE was calcuated in script.It try to wrap variable with double quotes but also failed. How to escaped them in awk?

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
user1179442
  • 473
  • 5
  • 16
  • 5
    You are interpolating the shell variables without any quoting whatsoever, so they look to Awk like mathematical expressions instead of strings. Indeed, 2021-6-1 evaluates to 2014. – tripleee Jun 09 '21 at 09:19
  • Wow! Just wanted to compliment you @tripleee for an excellent diagnosis of the "math" at play. To the original poster, look into `shellcheck` as a tool to help catch many issues like this. It is an eye-opening experience to learn all the potential errors that can happen when working with bash/shell. – user400575 Oct 06 '21 at 22:26
  • Thanks. The tool is available at http://shellcheck.net/ though of course you can install it locally as well. – tripleee Oct 07 '21 at 04:45

1 Answers1

2

You can use

awk -v sd="$START_DATE" -v ed="$END_DATE" '{gsub("{start_date}", sd); gsub("{end_date}", ed)}1' a.txt

where

  • -v sd="$START_DATE" -v ed="$END_DATE" - passes START_DATE and END_DATE variables to the awk script and initialize sd and ed variables with these values
  • gsub("{start_date}", sd); gsub("{end_date}", ed) - replace the placeholder text with these values
  • 1 replaces print command that is just shorter and does the same.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563