此脚本在MinGW-64中运行完美,但在Ubuntu中失败
awk: /home/username/chuleta/chuleta/glst.awk: line 22: illegal reference to variable a
awk: /home/username/chuleta/chuleta/glst.awk: line 23: illegal reference to variable a
...甚至在将shebang从#!/usr/bin/gawk -f
更改为#!/usr/bin/awk -f
以放弃GNU Awk和非GNU Awk之间的实现差异之后。
#!/usr/bin/awk -f
# generates list of terms related to a topic
# this funcion substitutes a with b in $0
func change(a,b) {
while (i=index($0,a))
$0 = substr($0,1,i-1) b substr($0,i+length(a))
}
{
# we delete the base folder (received in var RTO) from the input line
# and clean it of other stuff
change(RTO,"")
change(".txt","")
change("/"," ")
change("_"," ")
split($0,a," ")
# using arr as associative array by using same string as index
# this prevents duplicated strings and code is shorter
# since we don't have to maintain a counter for index
for (x in a) # this is line 22
arr[a[x]]=a[x] # this is line 23
}
END{
n=asort(arr,sarr)
for (x in sarr)
printf("%s ",sarr[x])
}
变量a
应该是使用空格分隔$0而得到的数组。
如前所述,这个错误在WinGW-64(Git for Windows使用的Linux bash模拟)中不会发生。
编辑:
通过Awk脚本传输的示例数据集如下所示:
/home/username/chuleta/chuleta-data/java/8/chuleta_foreach_loop.txt
/home/username/chuleta/chuleta-data/java/8/chuleta_basic_functional_interfaces_in_function_package.txt
/home/username/chuleta/chuleta-data/java/8/chuleta_advantages_new_date_time_api.txt
/home/username/chuleta/chuleta-data/java/8/chuleta_new_date_time_api.txt
/home/username/chuleta/chuleta-data/java/8/chuleta_solve_interface_default_methods_conflict.txt
/home/username/chuleta/chuleta-data/java/8/chuleta_lambdas_with_parameters.txt
RTO
传递给保存基本目录的脚本(home/username/chuleta/chuleta-data/
),然后从开头移除它,然后移除". txt",将"/"和"-"更改为空格,然后将得到的空格分隔单词列表拆分为数组("a"),它稍后被用来填充一个关联数组。基本上,我们得到一个空格分隔的子文件夹名称列表,不包括基本目录,例如"java 8 chuleta foreach循环"。产生的a
数组包含这五项。遍历a
的那些代码行只在Ubuntu中失败,而在MinGW-64中不会失败。
编辑2:
在Ubuntu 22.04、awk版本mawk 1.3.4 20200120、GNU bash版本5.1.16中的输出:
$ cat data.txt | ./program.awk -v RTO=/home/username/chuleta/chuleta-data
awk: ./prueba.sh: line 18: illegal reference to variable a
awk: ./prueba.sh: line 22: illegal reference to variable a
awk: ./prueba.sh: line 23: illegal reference to variable a
awk: ./prueba.sh: line 23: illegal reference to variable a
输出格式为MINGW64_NT-10.0 - 19044 3.1.7 - 340,awk版本GNU awk 5.0.0,API:2.0,GNU bash,版本4.4.23:
$ cat data.txt | ./program.awk -v RTO=/home/username/chuleta/chuleta-data
8 advantages api basic chuleta conflict date default foreach function functional in interface interfaces java lambdas loop methods new package parameters solve time with
1条答案
按热度按时间km0tfn4u1#
您的脚本使用了Mawk中没有的GNU Awk特性。
简单的修复方法可能是Ubuntu安装中的
apt-get install -y gawk
,并确保update-alternatives
指向gawk
。更详细地说,在main函数中将
a
重命名为k
消除了Mawk的直接问题,但它会抱怨asort
从未定义过(该函数是GNU Awk的扩展)。