【发布时间】:2017-08-25 15:45:50
【问题描述】:
我有工作代码
BEGIN { FS=";"; } # field separator
{
if (match($2, /[0-9]+/)) { # matching `ID` value
m=substr($2, RSTART, RLENGTH);
a[m]++; # accumulating number of lines for each `ID`
print > m"_count.txt"; # writing lines pertaining to certain `ID` into respective file
}
}
END {
for(i in a) {
print "mv "i"_count.txt "i"_"a[i]".txt" # renaming files with actual counts
}
}
现在我需要改变它来做这样的事情。 所以我有三个 ID 数组,每个数组意味着单独的文件夹来保存结果。
BEGIN { FS=";"; } # field separator
{
array1=(125 258 698 874)
array2=(956 887 4455 22)
array3=(111 444 558 966 332)
if ($1 == $2) {varR=$3} else {varR=$2}
if (match(varR, /[0-9]+/)) { # matching `ID` value
if ( varR in array1 ) {
FolderName = "folder1/"
m1=substr(varR, RSTART, RLENGTH);
a1[m1]++; # accumulating number of lines for each `ID`
print > (FolderName m1)"_count.txt"; # writing lines pertaining to certain `ID` into respective file
}
if ( varR in array2 ) {
FolderName = "folder2/"
m2=substr(varR, RSTART, RLENGTH);
a2[m2]++; # accumulating number of lines for each `ID`
print > (FolderName m2)"_count.txt"; # writing lines pertaining to certain `ID` into respective file
}
if ( varR in array3 ) {
FolderName = "folder3/"
m3=substr(varR, RSTART, RLENGTH);
a3[m3]++; # accumulating number of lines for each `ID`
print > (FolderName m3)"_count.txt"; # writing lines pertaining to certain `ID` into respective file
}
}
}
END {
for(i in a1) {
print "mv "i"_count.txt "i"_"a1[i]".txt" # renaming files with actual counts
}
for(i in a2) {
print "mv "i"_count.txt "i"_"a2[i]".txt" # renaming files with actual counts
}
for(i in a3) {
print "mv "i"_count.txt "i"_"a3[i]".txt" # renaming files with actual counts
}
}
因为我需要将匹配的 ID 保存到 txt 文件并放入所需的文件夹中 如果我有 100 个数组怎么办?我需要为每个重复代码吗?
【问题讨论】:
-
如果没有详细阅读您的代码,为避免重复代码,您可以构建一个 awk 用户函数,您可以为每个数组调用该函数。请参阅此使用函数的示例:stackoverflow.com/questions/42415826/…
标签: arrays linux multidimensional-array awk gawk