Evg*_*sky 8 awk shell-script trap
我相信Ctrl-C可以被困在 bash 脚本中。是否也可以将其捕获在 awk 脚本中以处理该事件?
例如,对于中止处理,但打印已经处理过的结果,而不是只是默默地退出?
Sté*_*las 11
我不知道有任何awk支持的实现。你可以写一个扩展gawk为,但在这里,我宁愿切换到另一种语言。
perlawk使用它的a2p脚本可以很容易地转换脚本。
例如,如果你有一个awk像这样的脚本:
{count[$0]++}
END {
for (i in count) printf "%5d %s\n", count[i], i
}
Run Code Online (Sandbox Code Playgroud)
a2p 它会给你类似的东西:
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if $running_under_some_shell;
# this emulates #! processing on NIH machines.
# (remove #! line above if indigestible)
eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
# process any FOO=bar switches
while (<>) {
chomp; # strip record separator
$count{$_}++;
}
foreach $i (keys %count) {
printf "%5d %s\n", $count{$i}, $i;
}
Run Code Online (Sandbox Code Playgroud)
您可以编辑以添加信号处理(并删除var=value我们不想要的参数处理,以及用于不支持的系统的部分#!):
#!/usr/bin/perl
sub report {
foreach $i (keys %count) {
printf "%5d %s\n", $count{$i}, $i;
}
}
$SIG{INT} = sub {
print STDERR "Interrupted\n";
report;
$SIG{INT} = 'DEFAULT';
kill('INT', $$); # report dying of SIGINT.
};
while (<>) {
chomp; # strip record separator
$count{$_}++;
}
report;
Run Code Online (Sandbox Code Playgroud)
另一种替代方法可以是中断的数据馈送到awk,并具有awk忽略SIGINT,等代替:
awk '{count[$0]++};END{for (i in count) printf "%5d %s\n", count[i], i}' file
Run Code Online (Sandbox Code Playgroud)
做:
cat file | (
trap '' INT
awk '{count[$0]++};END{for (i in count) printf "%5d %s\n", count[i], i}'
)
Run Code Online (Sandbox Code Playgroud)
Ctrl+C然后会杀死cat但不会awk。awk仍将继续处理仍在管道中的剩余输入。
要检测Ctrl+Cin awk,您可以执行以下操作:
(cat file && echo cat terminated normally) | (
trap '' INT
awk '{count[$0]++}
END{
if ($0 == "cat terminated normally") delete count[$0]
else print "Interrupted"
for (i in count) printf "%5d %s\n", count[i], i}'
)
Run Code Online (Sandbox Code Playgroud)