Linux 中的字符串重新排序

Linux 中的字符串重新排序

如何使用命令行更改行?
例如我有这些行:

    Acct-Status-Type = Start
    User-Name = "37XXXXXXX"
    Event-Timestamp = "Apr 12 2013 15:56:55 AMT"

我需要将顺序更改为:

    Event-Timestamp = "Apr 12 2013 15:56:55 AMT"
    User-Name = "37XXXXXXX"
    Acct-Status-Type = Start

我需要通过一个命令来完成此操作,sed、awk、perl 或类似的命令。

答案1

取决于您执行此操作的位置、频率、原因等,但将其放入脚本中不会有什么坏处。

无论如何,你可以做这样的事情来按定义的顺序打印。通过这种方法,您还可以选择仅打印选定的几个。例如只有 1 和 3:

一班轮:

awk -v order=312 \
'/^/{ln[NR]=$0}END{split(order,a,"");
 for(i in a)printf("%s\n",ln[a[i]]);}' \
 sample.txt

或者更容易阅读:

/^/{
    ln[NR] = $0
}
END{
    split(order,a,"");

    for(i in a)
        printf("%s\n",ln[a[i]]);
}

对于分割,如果超过 9 行,您可以添加一些分隔符。

例如:

split(order,a,"-");
# and call by:
awk -v order=3-13-21-12-2 ...

或者支持多个:

if (order ~ /-/)       split(order, a, "-"); # order has "-", split
else if (order ~ /\./) split(order, a, "."); # order has ".", split
else if (order ~/:/)   split(order, a, ":"); # order has ":", split
else                   split(order, a, "");  # none presume numbers split all

您还可以选择匹配行,如下所示:

BEGIN {
    i = 0;
}
/^\s*Acct-Status-Type/ {ln[++i] = $0 }
/^\s*User-Name/ {ln[++i] = $0 }
/^\s*Event-Timestamp/ {ln[++i] = $0 }
END {
    if (order ~ /-/)  split(order, a, "-");
    else if (order ~ /\./) split(order, a, ".");
    else if (order ~/:/) split(order, a, ":");
    else split(order, a, "")
    for (i in a)
        printf("%s\n", ln[a[i]]);
}

编辑:

对于最后一个示例,这可能会更好。 (还更新了分裂):

/^\s*Acct-Status-Type/ {ln[1] = $0 }
/^\s*User-Name/ {ln[2] = $0 }
/^\s*Event-Timestamp/ {ln[3] = $0 }
END {
    if (split(order, a, "-|:|,| |\\.") == 1) # Space require quoting of arg.
        split(order, a, "")
    for (i in a)
        printf("%s\n", ln[a[i]]);
}

答案2

使用 Python 和文件名作为程序的命令行参数:

import sys
with open(sys.argv[1]) as fp:
    for line in fp.readlines()[::-1]:
        sys.stdout.write(line)

或将其写回该文件:

import sys
with open(sys.argv[1]) as fp:
    lines = fp.readlines()
with open(sys.argv[1], 'w') as fp:
    for line in lines[::-1]:
        fp.write(line)

或作为从标准输入到标准输出的过滤器:

lines = sys.stdin.readlines()
for line in lines[::-1]:
    sys.stdout.write(line)

相关内容