0

I am trying to execute below command to replace variables in SQL with values passed from shell script but every time I am getting the same error as

sed: command garbled

sed -e 's/${BATCH_ID}/'${BATCH_ID}'/g; s/${LOAD_DATE}/TO_DATE\('"'"${LOAD_DATE}"'","'"YYYY-MM-DD"'"\)'/g' ${sqlFile}  >> ${SQL_DIR}/fmv_media_premise_ucg_update_temp.sql

Please can you help me in this. Thanks in advance.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user305990
  • 11
  • 2
  • 2
    First you should learn how and when to use quotes and single-quotes in bash. – fancyPants Oct 30 '17 at 07:18
  • Could you please explain what mistake have I done in using quotes above? – user305990 Oct 30 '17 at 07:22
  • I could, but it would be easier if you would simply read one of the thousands of articles regarding this topic on the internet. – fancyPants Oct 30 '17 at 07:23
  • See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Oct 30 '17 at 07:35
  • 1
    Please add sample input and your desired output for that sample input to your question. – Cyrus Oct 30 '17 at 07:36
  • @Cyrus Thanks. I have $sqlfile which is an insert statement and I have to replace variables in that sql file with the values I am passing from Unix script. – user305990 Oct 30 '17 at 08:17
  • Does your date or batch ID have a slash in it? Please read about how to create an MCVE ([MCVE]) and post one that allows us to see the problem you see. – Jonathan Leffler Oct 30 '17 at 23:13

2 Answers2

0

I have adapted your sed command in the following way:

sed -e "s/\${BATCH_ID}/${BATCH_ID}/g; s/\${LOAD_DATE}/TO_DATE(${LOAD_DATE},'YYYY-MM-DD')/g" ${sqlFile}  >> ${SQL_DIR}/fmv_media_premise_ucg_update_temp.sql

It will replace all occurrences of ${BATCH_ID} by the value contained in your BATCH_ID variable and change all ${LOAD_DATE} by the TO_DATE( value contained in LOAD_DATE, 'YYYY-MM-DD'), I hope this helps you! Cheers

One remark your are appending the output of your sed command to the fmv_media_premise_ucg_update_temp.sql file, are you sure you should not completely replace it? If it is the case just use > instead of >>

Allan
  • 12,117
  • 3
  • 27
  • 51
  • > does not matter here because every time I am deleting the temp file before running this script – user305990 Oct 30 '17 at 08:20
  • could you please give me some examples of the values contained in BATCH_ID and LOAD_DATE? I am pretty sure they contain some character that sed uses internally causing your error... If it this the case, before calling sed with the variables you should create a function that would escape all those characters using "\" – Allan Oct 31 '17 at 00:29
0

Do you have envsubst? This will provide you with

envsubst < "${sqlFile}"

That will be better than

source <(echo "echo \"$(< ${sqlfile})\"")

The last one will expand more things.

Walter A
  • 19,067
  • 2
  • 23
  • 43