在Unix Korn Shell中实现文本文件行排序的技术需求
在Korn Shell中按首列数字排序文本行
没问题,这事儿在Korn Shell里用sort命令就能完美解决!你的文本行是用|分隔的字段,首列是数字,我们只需要告诉sort按这个数值字段排序就行。
具体命令
假设你的文件名为input.txt,执行以下命令:
sort -t'|' -k1,1n input.txt
参数解释:
-t'|':指定字段分隔符为|-k1,1n:表示仅对第1个字段进行数值排序(n代表numeric sort),这样就不会把数字当字符串排序(比如避免"10"排在"2"前面的问题)
验证效果
你的示例输入:
3|"Apple"|"iphoneX"|"This is the latest phone."|"California"
2|"Samsung"|"s9"|"This phone isn't so good. It hangs for no reason when old."|"Texas"
1|"OnePlus"|"5t"|"This is a good android phone."|"Arizona"
运行命令后,输出就是你想要的结果:
1|"OnePlus"|"5t"|"This is a good android phone."|"Arizona"
2|"Samsung"|"s9"|"This phone isn't so good. It hangs for no reason when old."|"Texas"
3|"Apple"|"iphoneX"|"This is the latest phone."|"California"
额外小技巧
如果想直接将排序结果覆盖原文件(注意:操作前最好备份原文件!),可以用-o参数指定输出文件:
sort -o input.txt -t'|' -k1,1n input.txt
这样就不用手动写重定向(比如sort ... > input.txt),更安全可靠。
内容的提问来源于stack exchange,提问作者Novice_Techie
相关产品推荐
相关产品推荐

