简体   繁体   English

Bash 脚本:如何在排序文本或 csv 文件时跳过 header 行,同时将其保留在 output 中

[英]Bash script: how to skip a header line when sorting a text or csv file, while retaining it in the output

(Adapted from this: Join Manual, Header lines ). (改编自: 加入手册,Header 行)。

I am sorting a file called file1 with this content:我正在使用以下内容对名为 file1 的文件进行排序:

Name   Age
Charlie 34
Alice   25

If I just write:如果我只是写:

sort -k2b,2 file1

I get:我得到:

Alice   25
Charlie 34
Name   Age

I can exclude the header from the sort like so:我可以像这样从排序中排除 header:

head -1 file1;(sed -n '2,$p' file1|sort -k2b,2)

But the example in the gnu manual is this:但是 gnu 手册中的示例是这样的:

( sed -u 1q; sort -k2b,2 ) < file1

Why does that work?为什么这样行得通?

I would think that I would get this instead from the command-line:我想我会从命令行得到这个:

Name   Age
Alice   25
Charlie 34
Name   Age

The sed consumes the first line of stdin, then the sort consumes the rest? sed 消耗 stdin 的第一行,然后排序消耗 rest?

You could have sed print the header, then sort the rest.您可以让 sed 打印 header,然后对 rest 进行排序。

sed -n '1p' file1; sort <(sed '1d' file1)
Name   Age
Alice   25
Charlie 34

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 bash脚本-寻求有关从csv文件提取列以及如何跳至当前while循环中的下一行的建议 - bash script - seeking advice on extracting columns from csv file and how to skip to next line in current while loop 如何在bash脚本输出中包含tsv / csv标头 - How to include tsv/csv header in bash script output 如何将 bash 脚本的输出写入包含标题的 CSV 文件的第二行? - How do I write an output from bash script to the second line of the CSV file that contains headers? Bash-如何在写入csv时跳过一列 - Bash - How to skip a column while writing to csv 使用bash脚本对CSV文件进行排序和差异 - Sorting and diff of CSV file using bash script Bash脚本读取文本文件,然后将每一行输出到变量中 - Bash script to read a text file and then output each line into variables 如何在 bash 脚本中使用 jq 将 json output 写入 CSV 文件? - How to write json output to a CSV file using jq in a bash script? Bash脚本 - 如何在使用getopts时逐行读取文件 - Bash script - how to read file line by line while using getopts 如何使用bash脚本将文本文件转换为csv文件 - How to convert text file to csv file using bash script 如何在使用 csv 脚本处理后删除 csv 文件中的一行 bash 脚本 - How to delete a line in a csv file after processing it with a Linux bash script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM