【问题标题】:Re-arrange files starting from desired file with awk one-liner使用 awk one-liner 从所需文件开始重新排列文件
【发布时间】:2020-07-24 19:12:49
【问题描述】:

假设我们在 unix/linux 文件夹中有这些常规排序的文件。

A.txt
B.txt
C.txt
D.txt
a.txt
b.txt
c.txt

command D.txt 必须排序为:

D.txt -> begin with selected file
a.txt
b.txt
c.txt
A.txt -> append remaining files in order
B.txt
C.txt

command b.txt 必须排序为:

b.txt
c.txt
A.txt
B.txt
C.txt
D.txt
a.txt

我在下面尝试了这样的脚本,但 awk 似乎没有以我想要的方式重新排列输出。命令总是按常规顺序排序。

#!/bin/sh
export fname="$1"
find . -maxdepth 1 -type f | sort | awk -v ref="./$fname" '($0 > ref) {print $0} ($0 < ref) {print $0}'

【问题讨论】:

    标签: sorting awk


    【解决方案1】:

    缓冲行直到ref,打印ref 和到达的连续行,并在最后打印缓冲区。

    awk -v ref="./$fname" '$0==ref{f=1} f{print;next} {buf=buf $0 ORS} END{printf "%s",buf}'
    

    演示:

    $ seq 5 | awk -v ref=3 '$0==ref{f=1} f{print;next} {buf=buf $0 ORS} END{printf "%s",buf}'
    3
    4
    5
    1
    2
    

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多