首页 > 解决方案 > 如何将 .txt 文件中的行读入此 bash 脚本?

问题描述

我有这个连接到 postgre sql db 并执行查询的 bash 脚本。我希望能够将 .txt 文件中的行作为参数读入查询中。最好的方法是什么?非常感谢您的帮助!我在下面有我的示例代码,但是它不起作用。

#!/bin/sh

query="SELECT ci.NAME_VALUE NAME_VALUE FROM certificate_identity ci WHERE ci.NAME_TYPE = 'dNSName' AND reverse(lower(ci.NAME_VALUE)) LIKE reverse(lower('%.$1'));"

(echo $1; echo $query | \
    psql -t -h crt.sh -p 5432 -U guest certwatch | \
    sed -e 's:^ *::g' -e 's:^*\.::g' -e '/^$/d' | \
    sed -e 's:*.::g';) | sort -u

标签: sqlbash

解决方案


考虑到该文件每行只有一个 sql 查询:

while read -r line; do echo "${line}" | "your code to run psql here"; done < file_with_query.sql

这意味着:在逐行读取 file_with_query.sql 的内容时,对每一行执行一些操作。


推荐阅读