重新排列文件内容

重新排列文件内容

我想按行重新排列文件的内容(见下文),最好不使用 Perl 或 Python(我不被允许...不要问。)

输入文件包含无序的标题行和包含备份操作结果的行。输出文件应包含如下所示的有序行。

原始文件:

Completed Backups
Backups with Warnings
Failed Backups
Server A backup was completed with warnings
Server B backup was successful
Server C backup failed
Server D backup was completed with warnings

最终结果:

Completed Backups
Server B backup was successful
Backups with Warnings
Server A backup was completed with warnings
Server D backup was completed with warnings
Failed Backups
Server C backup failed

答案1

恶意的 grep 滥用啊。我原来的脚本依赖于 grep 区分大小写的事实,并且您的文本大小写很奇怪,而且这些大小写都是独一无二的。我做了第二个变体(您可以在编辑跟踪中看到旧版本),它使用了您需要重新排列的更大块的行。“正确”地执行它可能会更快,因为它会针对每个 grep 命令遍历整个文本文件 - 对于大文件,这意味着要循环 6 次才能重新组织它。

应该在 Windows 或 Linux 上使用一些小修改,或者直接复制粘贴。假设您的源文件名为 original.txt,输出为 new.txt。如果您需要按字母顺序排列行,您可以对 grep 出来的行进行排序。>> 附加到新行

 #! /bin/sh

    grep "Completed Backups" original.txt >> new.txt
    grep "backup was successful" original.txt >> new.txt
    grep "Backups with Warnings" original.txt >> new.txt
    grep "backup was completed with warnings" original.txt >> new.txt
    grep "Failed Backups"  original.txt >> new.txt
    grep "backup failed" original.txt >> new.txt

如果我是你,我可能会等待正确的基于 sed 或 awk 的答案。我还会尝试使用更大的字符串子集

答案2

不幸的是sed,或者awk在这里不会有太大帮助,因为重新排序行的最简单方法是像 Journeyman Geek 所展示的那样通过多次传递来处理输入。

这里只是一种略有不同的替代方案,它只打开一次输出文件。另一种方法是在标题中,在这里重新创建它们,而不是从源传输它们。

#!/bin/sh

output=new.txt
input=original.txt

{
  echo "Completed Backups"
  grep "Server .* backup was successful" < "$input"

  echo "Backups with Warnings"
  grep "Server .* backup was completed with warnings" < "$input"

  echo "Failed Backups"
  grep "Server .* backup failed" < "$input"
} > "$output"

除了在脚本中指定输入和输出之外,您还可以从命令行读取它们:

output="$1"
input="$2"

相关内容