How can I replace string in KSH file from a sql file?

Viewed 31

Here is my code in ksh file

current_year=$(date +%Y)
current_month=$(date +%m)
sql=$(cat $script_path | sed -i 's/&1/current_year/g' | sed -i 's/&2/current_month/g')

Fisrt, I cat a sql file in KSH file and then I want the a string called "&1" and "&2" in sql file are replaced by current_year and current_month. But it doesn't work, hope I can find a solution here, thanks very much.

The reason I did that is I don't want to pass the parameter to sql file from ksh file, I just want a simple way to replace the string in ksh file.

1 Answers

I changed your script to:

script_path=script.txt

current_year=$(date +%Y)
current_month=$(date +%m)
sql=$(sed -e "s/\&1/${current_year}/g" \
    -e "s/\&2/${current_month}/g" "${script_path}")
echo "${sql}"
  • You don't need cat, I put it as a stdin read (< ${script_path}) for sed.
  • Search and replace for sed is -e not -i which is for inline editing.
  • Use double quotes, not single quotes. That allows variable substitution.
  • Escape the &, by doing \& so it isn't interpreted.

Here is a sample input file and the result:

# cat script.txt; ksh sq.sh
select * from &1 where &2;
select script.txt sq.sh from 2022 where 09;
Related