Shell脚本,使用awk进行对角线搜索

时间:2014-10-11 17:06:48

标签: linux bash shell awk diagonal

我正在寻找一种从这个字母块中获得对角线组合的方法:

a b c d e f 
h i j k l m 
o p q r s t 
v w x y z a 
c d e f g h 
j k l m n o 

我有这个:awk '{++f; print $(f + 0)}' file.txt

但这只会让我(如果我可以增加,f + 0,不知何故增加1次,6次):

a i q y g o
b j r z h
c k s a
d l t
e m 
f

我需要另一半......就像这样(不必按此顺序:

a i q y g o
h p x f n
b j r z h
o w e m
c k s a
v d l
d l t
c k
e m
j 
f

3 个答案:

答案 0 :(得分:2)

您可以使用GNU datamash

$ datamash -t' ' transpose < file
a h o v c j
b i p w d k
c j q x e l
d k r y f m
e l s z g n
f m t a h o

答案 1 :(得分:1)

perl -lane'
  push @r, [@F];
END {
  for my $n (0 .. $#r) {
    my (@x,@y);
    for (0 .. $#r) {
      push @x, $r[$n+$_][$_];
      push @y, $r[$_][$n+$_];
    }
    print "@x";
    print "@y" if $n;
  }
}
' file

输出

a i q y g o
h p x f n
b j r z h
o w e m
c k s a
v d l
d l t
c k
e m
j
f

答案 2 :(得分:0)

这是阵列的工作。

#!/usr/bin/awk -f

# Print diagonals from a square of text. 
# This script has no error checking.
# Written by PM 2Ring 2014.10.13

{
    for(i=1; i<=NF; i++) 
        a[NR,i] = $i
}

END{
    for(i=1; i<=NR; i++)
    {
        for(j=1; i+j-1<=NR; j++)
            printf "%s ", a[i+j-1, j]
        print ""
        if (i == 1) 
            continue
        for(j=1; i+j-1<=NR; j++)
            printf "%s ", a[j, i+j-1]
        print ""
    }
}

这是上述代码的一个版本,用于将每个对角字存储在一个数组中。

#!/usr/bin/awk -f

# Print diagonals from a square of text. 
# This script has no error checking.
# Written by PM 2Ring 2014.10.13

{
    for(i=1; i<=NF; i++) 
        a[NR,i] = $i
}

END{
    k = 1
    for(i=1; i<=NR; i++)
    {
        word = ""
        for(j=1; i+j-1<=NR; j++)
            word = word a[i+j-1, j]
        words[k++] =  word

        if (i == 1) 
            continue

        word = ""
        for(j=1; i+j-1<=NR; j++)
            word = word a[j, i+j-1]
        words[k++] = word   
    }

    numwords = k
    for (k=1; k<numwords; k++)
        print words[k]
}

<强>输出

aiqygo
hpxfn
bjrzh
owem
cksa
vdl
dlt
ck
em
j
f

打印正交对角线,例如&#39; flrxdj&#39;,留给读者练习。

...

这是一个打印给定单词中所有子词的函数。

#!/usr/bin/awk -f

# Print subwords of a given word 
# Written by PM 2Ring 2014.10.13

function print_subwords(s,  i, j, len)
{
    len = length(s)
    for (i=1; i<=len; i++)
    {
        print "Length:", i
        for (j=1; i+j-1 <= len; j++)
            print substr(s, j, i)
    }
}

BEGIN{
    print_subwords("ABCD") 
}

<强>输出

Length: 1
A
B
C
D
Length: 2
AB
BC
CD
Length: 3
ABC
BCD
Length: 4
ABCD