交换无限数量的列

use*_*519 12 sed awk text-processing columns

我有一个带列的文件。请参阅下面的示例:

a b c ... z  
1 2 3 ... 26
Run Code Online (Sandbox Code Playgroud)

我想交换第一个成为最后一个,第二个成为最后一个之前的所有列......等等。

z y x ... a  
26 25 24 ... 1
Run Code Online (Sandbox Code Playgroud)

是否有一个班轮(awksed)可以做到这一点?
我知道awk当只有几列时可以使用,但我希望能够对具有数千列的文件执行此操作。

tac这对于线条来说是完美的。
我想我正在寻找列的等效项。

rev 对我没有用,因为它还交换了列中的内容。

rus*_*ush 15

awk '{for(i=NF;i>0;i--)printf "%s ",$i;print ""}' file
Run Code Online (Sandbox Code Playgroud)


jmp*_*jmp 10

你可以用一个小的python脚本来做到这一点:

#!/usr/bin/env python

# Swaps order of columns in file, writes result to a file.
# usage: program.py input_file output_file

import sys, os

out = []

for line in open(sys.argv[1], 'r'):
    fields = line.split()
    rev = ' '.join(list(reversed(fields)))
    out.append(rev)

f = open(sys.argv[2], 'w')
f.write(os.linesep.join(out))
Run Code Online (Sandbox Code Playgroud)


Pad*_*118 7

如果你不介意 python,那么这个单行会颠倒每一行中空格分隔列的顺序:

paddy$ cat infile.txt 
a b c d e f g h i j k l
1 2 3 4 5 6 7 8 9 10 11 12
a e i o u
paddy$ python3 -c 'with open("infile.txt") as f: print("\n".join(" ".join(line.rstrip().split()[::-1]) for line in f))'
l k j i h g f e d c b a
12 11 10 9 8 7 6 5 4 3 2 1
u o i e a
paddy$ 
Run Code Online (Sandbox Code Playgroud)

以上也适用于python2.7:

paddy$ python2.7 -c 'with open("infile.txt") as f: print("\n".join(" ".join(line.rstrip().split()[::-1]) for line in f))'
l k j i h g f e d c b a
12 11 10 9 8 7 6 5 4 3 2 1
u o i e a
paddy$ 
Run Code Online (Sandbox Code Playgroud)


Bir*_*rei 4

一种方法是使用awk.

内容infile

a b c d e f g h i j k l
1 2 3 4 5 6 7 8 9 10 11 12
a e i o u
Run Code Online (Sandbox Code Playgroud)

运行以下awk命令:

awk '{
    ## Variable 'i' will be incremented from first field, variable 'j'
    ## will be decremented from last field. And their values will be exchanged.
    ## The loop will end when both values cross themselves.
    j = NF; 
    for ( i = 1; i <= NF; i++ ) { 
        if ( j - i < 1 ) { 
            break;
        } 
        temp = $j; 
        $j = $i; 
        $i = temp; 
        j--; 
    }
    print;
}' infile
Run Code Online (Sandbox Code Playgroud)

结果如下:

l k j i h g f e d c b a
12 11 10 9 8 7 6 5 4 3 2 1
u o i e a
Run Code Online (Sandbox Code Playgroud)