AWK 3.1.7 - 单个中的多个循环

时间:2016-06-25 23:56:41

标签: awk gawk

我正在尝试使用以下代码对2个数组进行排序:

 n = asorti (pacben,pacsor)
 m = asorti (pacben2,pacsor2)

我需要对它们进行排序,最好是在一起。我知道我可以分别使用以下内容单独执行:

 n = asorti (pacben,pacsor)
for (p = 1;p <= n; p++) {
blah
}
 m = asorti (pacben2,pacsor2)
for (p2 =1;p2 <= m; p2++) {
blah
}

但是当我尝试以下内容时:

 n = asorti (pacben,pacsor)
 m = asorti (pacben2,pacsor2)
for (p = 1;p <= n;p++ && p2 = 1;p2 <= m;p2++) {
blah
}

我收到以下错误:

awk: cmd. line:25:                         for (p = 1;p <= n;p++ && p2 = 1;p2 <= m; p2++) {
awk: cmd. line:25:                                                        ^ syntax error
awk: cmd. line:25:                         for (p = 1;p <= n;p++ && p2 = 1;p2 <= m; p2++) {
awk: cmd. line:25:                                                                      ^ syntax error

任何和所有帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

保持简单。有各种可能的解决方案,取决于你真正想要的是什么以及blah可能做什么,但基于你接受@JonathanLeffer's answer,这必须是你想要的:

n = asorti (pacben,pacsor)
m = asorti (pacben2,pacsor2)
for (p = 1;p <= n && p <=m; p++) {
    blah
}

还考虑如何处理不同大小的数组:

$ cat tst.awk
BEGIN{
    n = split("A C E",a)
    m = split("B D F G H",b)
    for (p=1;p<=n && p<=m;p++) {
        print a[p] ORS b[p]
    }
    for (;p <= (n > m ? n : m);p++) {
        print (n > m ? a[p] : b[p])
    }
}

$ awk -f tst.awk
A
B
C
D
E
F
G
H

答案 1 :(得分:2)

在C中,您需要修改:

var selectedIndexPath: NSIndexPath?

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    selectedIndexPath = indexPath
}

func scrollToCell(){

      if let index = selectedIndexPath{
 customViewCollectionView.scrollToItemAtIndexPath(index, atScrollPosition: .CenteredVertically, animated: false)
    }else{
        print("A cell hasnt been selected yet") 
  }
}

成:

for (p = 1;p <= n;p++ && p2 = 1;p2 <= m;p2++) {

这是逗号运算符的标准用法之一。但是,for (p = 1, p2 = 1; p <= n && p2 <= m; p1++, p2++) { 似乎不接受逗号运算符。

Mac OS X(BSD)awk

awk

GNU $ awk -v n=2 -v m=3 'BEGIN { for (p = 1, p2 = 1; p <= n && p2 <= m; p1++, p2++) print p1, p2}' awk: syntax error at source line 1 context is BEGIN { for (p = >>> 1, <<< awk: illegal statement at source line 1 awk: illegal statement at source line 1 $

awk

awk的POSIX规范在运算符列表中不包含逗号运算符。

您可以使用:

$ awk -v n=2 -v m=3 'BEGIN { for (p = 1, p2 = 1; p <= n && p2 <= m; p1++, p2++) print p1, p2}'
awk: cmd. line:1: BEGIN { for (p = 1, p2 = 1; p <= n && p2 <= m; p1++, p2++) print p1, p2}
awk: cmd. line:1:                   ^ syntax error
awk: cmd. line:1: BEGIN { for (p = 1, p2 = 1; p <= n && p2 <= m; p1++, p2++) print p1, p2}
awk: cmd. line:1:                                                    ^ syntax error
$

这利用了$ awk -v n=2 -v m=3 'BEGIN { for (p1 = p2 = 1; p1 <= n && p2 <= m; p1++ && p2++) print p1, p2}' 1 1 2 2 $ p1被初始化为相同值的事实,并且p2p1在增量部分中都是非零的。循环。