如何在有标题行的文件上使用Unix排序命令



如何通过排序省略csv文件中的标题行?

到目前为止,我有这个:

sort -o  ./trans.csv -k 1,1n ./trans.csv

除了标题行也被排序之外,它工作得很好。

要在输出中保留标题,并对所有非标题行进行排序:

# create a temporary file to store output to
infile="trans.csv"
tempfile=$(mktemp "${infile}.XXXXXX")
if {
IFS= read -r header            # read header from input to variable
printf '%sn' "$header"        # write header from variable to output
sort -k 1,1n                   # pass all other input to output through sort
} <"$infile" >"$tempfile"; then  # if sort reports success (exit status 0)
mv -- "$tempfile" "$infile"    # ...then atomically rename over input
else                             # if sort fails...
echo "ERROR: Output file and input file have different line counts" >&2
rm -f "$tempfile"              # then delete the temporary file.
false                          # and ensure that $? reflects a failure
fi

请注意,if块只检查sort的退出状态,因为我们更关心数据是否通过,而不是标头。如果不喜欢使用&&s而不是换行符来附加块中的项目。

( sed -u 1q; sort -k 1,1n ) < trans.csv > trans-sorted.csv

(GNU核心工具手册中建议)

-u选项对于不丢失数据非常重要(请参阅注释)。

或:

( read header; echo $header; sort -k 1,1n ) < trans.csv > trans-sorted.csv

要使用相同的文件名:添加&& mv trans-sorted.csv trans.csv:

( read header; echo $header; sort -k 1,1n ) < trans.csv > trans-sorted.csv && mv trans-sorted.csv trans.csv

您可以使用tail跳过第一行:

tail -n +2 ./trans.csv | sort -o ./trans.csv -k 1,1n

-n +2表示"从第二行输入开始输出"。

您可以这样尝试:

(read line;echo $line;(while read line;do echo $line;done) | sort -k 1,1n)<infile

最新更新