与 awk 脚本作斗争需要帮助才能做到这一点只需要您的建议或逻辑

Ham*_*bir 1 awk

我有一个sql文件来过滤数据

-- Edit this file by adding your SQL below each question.
-------------------------------------------------------------------------------

-------------------------------------------------------------
-- The following queries are based on the 1994 census data.
-------------------------------------------------------------

.read 1994
-census-summary-1.sql

-- 4. what is the average age of people from China?
select avg(age)
from census
where native_country ='China';

-- 5. what is the average age of people from Taiwan?
select avg(age)
from census
where native_country ='Taiwan';

-- 6. which native countries have "land" in their name?
select distinct(native_country)
from census
where native_country like '%land%';

--------------------------------------------------------------------------------------
-- The following queries are based on the courses-ddl.sql and courses-small.sql data
--------------------------------------------------------------------------------------

drop table census;
.read courses-ddl.sql
.read courses-small-1.sql

-- 11. what are the names of all students who have taken some course? Don't show duplicates.
select distinct(name)
from student
where tot_cred > 0;

-- 12. what are the names of departments that offer 4-credit courses? Don't list duplicates.
select distinct(dept_name)
from course
where credits=4;

-- 13. What are the names and IDs of all students who have received an A in a computer science class?
select distinct(name), id
from student natural join takes natural join course  
where dept_name="Comp. Sci." and grade="A";

Run Code Online (Sandbox Code Playgroud)

如果我跑

./script.awk -v ID=6 文件.sql

请注意,问题 ID 作为命令行上的变量 ID 传递给 awk 脚本,如下所示: -v ID=6

我怎样才能得到像 Result 这样的结果:

select distinct(native_country) from census where native_country like '%land%';

Rav*_*h13 5

使用您显示的示例和 GNU 中的代码awk,请尝试awk使用其match函数来执行以下 GNU 代码。您希望确保在输入文件的行中检查变量的值idawk另外,我还习惯于exit获取/打印第一个匹配项并退出程序以节省一些时间/周期,如果您有多个匹配项,则只需从以下代码中将其删除即可。

awk -v RS= -v id="6" '
match($0,/(\n|^)-- ([0-9]+)\.[^\n]*\n(select[^;]*;)/,arr) && arr[2]==id{
  gsub(/\n/,"",arr[3])
  print arr[3]
  exit
}
'  Input_file
Run Code Online (Sandbox Code Playgroud)