There are a lot of variations on this question, but I wanted to ask it here anyways because I am so close (!) to finding a solution on this one - I just need a little nudge.
Scenario
I have several text SQL files that I use to run reports on a Postgres database hosted with Heroku. One of the SQL files currently looks like this:
SELECT
(SELECT COUNT(*) FROM metrics WHERE(organization_id = o.id AND year = ${sql_year})) AS metrics,
(SELECT COUNT(*) FROM my_metrics WHERE(organization_id = o.id)) AS quarterly_metrics,
(SELECT COUNT(*) FROM quarterly_metrics WHERE(organization_id = o.id AND year = ${sql_year})) AS quarterly_metrics,
(SELECT COUNT(*) FROM quarterly_text_metrics WHERE(organization_id = o.id AND year = ${sql_year})) AS quarterly_text_metrics,
(SELECT COUNT(*) FROM budgets WHERE(organization_id = o.id AND year = ${sql_year})) AS budgets,
(SELECT COUNT(*) FROM goals WHERE(goalable_type = 'Organization' AND goalable_id = o.id AND year = ${sql_year})) AS goals
FROM
organizations AS o
WHERE
o.id = ${sql_org_id}
;
I would like to use a process like this:
export sql_org_id=1; export sql_year=2013
cat reports/my_report.sql | sed -e "s/\(\${[a-zA-Z_]*}\)/`eval "echo '\1'"`/" | heroku pg:psql
So that I can just pipe the SQL to Heroku for the report, replacing all the variables with their corresponding ENV vars that were exported just before running the script (so that I can simply change the variables on the fly and run additional reports instead of editing the SQL file).
My Problem
So the issue is that I am almost there, but I can't quite get it. The sed expression I have works when I use echo like this:
export sql_year=2013
echo "SELECT ${sql_year} AS year" | sed -e "s/\(\${[a-zA-Z_]*}\)/`eval "echo '\1'"`/"
But I can't get it to work with cat on the entire file contents:
export sql_org_id=1; export sql_year=2013
cat reports/my_report.sql | sed -e "s/\(\${[a-zA-Z_]*}\)/`eval "echo '\1'"`/"
Am I missing something when using sed with cat? Please help!
UPDATE: I am on Mac OS X 10.8
cataltogether and just using thesed -e 'expression_here' file_namesyntax? You're guilty of a useless use of cat there. Also, it may not be necessary with the particular example you specified but semantically, I think you need agmodifier on yoursedregex.sedeither. It was covered earlier in this question today: unix.stackexchange.com/questions/85082/…echo foo | sed "s/foo/$(uptime)/"