如何通过排序省略csv文件中的标题行?
到目前为止我有这个:
sort -o ./trans.csv -k 1,1n ./trans.csv
Run Code Online (Sandbox Code Playgroud)
除了标题行之外,它也能很好地排序.
要在输出中保留标题,并对所有非标题行进行排序:
# 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
Run Code Online (Sandbox Code Playgroud)
请注意,该if块仅检查退出状态sort,理论上我们更关心数据是否通过而不是标头.&&如果不是首选,请考虑使用s而不是换行来附加块中的项目.
| 归档时间: |
|
| 查看次数: |
581 次 |
| 最近记录: |