【问题标题】:How do I sort a file after a certain row in bash?如何在bash中的某一行之后对文件进行排序?
【发布时间】:2014-08-07 22:12:12
【问题描述】:

我正在尝试对文件进行排序并将输出存储到tmp 文件中。这是我的文件的样子:

this_is_my_file(无扩展名)

Names   Last_Name_Initial
---
Alex   G
Nick   D
Jon   J
Cain   V
Anderson   S
Chris   W

我知道对文件进行排序的命令是sort -n $PWD/this_is_my_file -o tmp,但是如何在--- 之后开始排序?还有一个后续问题,如果您要比较的文件没有扩展名,您如何区分文本文件或 xml 文件?

【问题讨论】:

  • 您可以按第二列排序,因为它没有---
  • @Rahul 我想对第一列进行排序

标签: linux bash shell scripting suse


【解决方案1】:

你可以使用:

head -n 2 file && tail -n +3 file | sort
Names   Last_Name_Initial
---
Alex   G
Anderson   S
Cain   V
Chris   W
Jon   J
Nick   D

它的工作如下:

  1. 使用 head -n 2 获取前 2 个标题行
  2. 使用tail -n +3 获取从第 3 行开始的所有行
  3. 管道tail 的输出与sort
  4. 使用&& 将头部的输出与tail+sort 合并

要重定向输出,您可以在 shell {...} 中使用分组

{ head -n 2 file && tail -n +3 file | sort; } > output

【讨论】:

  • 答案中添加了解释。
  • 如何将输出重定向到另一个文件? head -n 2 file && tail -n +3 file | sort > tmp?
【解决方案2】:

您可以使用分组结构:

{
    # read and print the first 2 lines
    read line; echo "$line"
    read line; echo "$line"
    # and sort the rest
    sort
} < this_is_my_file

还有,awk:

awk 'NR <= 2 {print; next} {print | "sort"}' this_is_my_file

后续回答:通常,在 unix-y 系统上,名称文件不保证文件的内容。但是,您可以看到 file 命令对文件的说明:

$ cat > contains_xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<foo>
<bar>baz</bar>
</foo>
$ file contains_xml
contains_xml: XML document text
$ cat > not_really.xml
this is plain text
$ file not_really.xml
not_really.xml: ASCII text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2012-11-01
    • 2015-06-29
    • 2021-05-03
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多