简体   繁体   English

Linux-数值排序然后覆盖文件

[英]Linux - numerical sort then overwrite file

I have a csv file with a general format 我有一个具有常规格式的csv文件

date,  
2013.04.04,
2013.04.04,
2012.04.02,
2013.02.01,
2013.04.05,
2013.04.02,

a script I run will add data to this file which will not necessarily be in date order. 我运行的脚本会将数据添加到此文件中,但不一定按日期顺序。 How can I sort the file into date order (ignoring the header) and overwrite the existing file rather than writing to STDOUT 如何将文件按日期顺序排序(忽略标题)并覆盖现有文件,而不是写入STDOUT

I have used awk 我用过awk

awk 'NR == 1; NR > 1 {print $0 | "sort -n"}' file > file_sorted
mv file_sorted file

Is there a more effective way to do this without creating an additional file and moving? 有没有更有效的方法来执行此操作而无需创建其他文件并移动?

You can do the following: 您可以执行以下操作:

sort -n -o your_file your_file

-o defines the output file and is defined by POSIX , so it is safe to use (no original file mangled). -o定义输出文件, 并由POSIX定义 ,因此可以安全使用(不破坏原始文件)。

Output 输出量

$ cat s
date,  
2013.04.04,
2013.04.04,
2012.04.02,
2013.02.01,
2013.04.05,
2013.04.02,

$ sort -n -o s s

$ cat s
date,  
2012.04.02,
2013.02.01,
2013.04.02,
2013.04.04,
2013.04.04,
2013.04.05,

Note that there exists a race condition if the script and the sorting is running at the same time. 请注意,如果脚本和排序同时运行,则存在竞争条件。

If the file header sorts before the data, you can use the solution suggested by fedorqui as sort -o file file is safe (at least with GNU sort, see info sort ). 如果文件头在数据之前排序,则可以使用fedorqui建议的解决方案,因为sort -o file file是安全的(至少使用GNU sort,请参阅info sort )。

Running sort from within awk seems kind of convoluted, another alternative would be to use head and tail (assuming bash shell): awk内运行sort似乎有些麻烦,另一种选择是使用headtail (假设bash shell):

{ head -n1 file; tail -n+2 file | sort -n; } > file_sorted

Now, about replacing the existing file. 现在,关于替换现有文件。 AFAIK, You have two options, create a new file and replace old file with new as you describe in your question, or you could use sponge from moreutils like this: AFAIK,您有两个选择,创建一个新文件,然后按照问题中的描述用新文件替换旧文件,或者可以使用moreutils sponge ,如下所示:

{ head -n1 file; tail -n+2 file | sort -n; } | sponge file

Note that sponge still creates a temporary file. 请注意, sponge仍然会创建一个临时文件。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM