gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:42:15 24 4
gpt4 key购买 nike

如何通过排序省略 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 '%s\n' "$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 block 仅检查 sort 的退出状态,理论上我们更关心数​​据是否通过,而不是 header 。如果不是首选,请考虑使用 && 而不是换行符来附加 block 中的项目。

关于bash - 如何在具有标题行的文件上使用 Unix 排序命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com