英文:
sort text file based on specific filenames
问题
你可以使用sort
命令以及-t
和-k
选项来按照你的需求排序。在这种情况下,你可以使用以下命令:
sort -t'/' -k4,4n -k5,5n -k6,6n your_file.txt
这个命令将文件按照斜杠分隔的第四、五和六个字段来排序,这将按照你期望的方式对文件进行排序。请确保将your_file.txt
替换为你的实际文件名。
英文:
I have a bit of a weird problem. I hve a text file which looks like so:
/path/to/dir/0/100_something.dat,0.6
/path/to/dir/0/101_something.dat,0.6
/path/to/dir/0/102_something.dat,0.6
/path/to/dir/1/100_something.dat,0.6
/path/to/dir/1/101_something.dat,0.6
/path/to/dir/1/102_something.dat,0.6
/path/to/dir/2/100_something.dat,0.6
/path/to/dir/2/101_something.dat,0.6
/path/to/dir/2/102_something.dat,0.6
and I would like to sort it so that it looks like so:
/path/to/dir/0/100_something.dat,0.6
/path/to/dir/1/100_something.dat,0.6
/path/to/dir/2/100_something.dat,0.6
/path/to/dir/0/101_something.dat,0.6
/path/to/dir/1/101_something.dat,0.6
/path/to/dir/2/101_something.dat,0.6
/path/to/dir/0/102_something.dat,0.6
/path/to/dir/1/102_something.dat,0.6
/path/to/dir/2/102_something.dat,0.6
How can I achieve this in bash please? I used to sorting numerically via sort -n
but I am not sure how to sort the above case since the field seperator and the field are not exactly useful (at least straightaway)
答案1
得分: 1
如果路径元素数量恒定且每行的元素数量相同,则仅使用sort
命令就可以完成此操作。
在您的示例中,每行包含6个由/
分隔的路径元素(行以一个空元素开头)。
您似乎希望按元素6进行排序,然后按元素5进行次级排序,都是按数值排序。
所以:
sort -t/ -n -k6,6 -k5,5 inputfile
-k
选项可以接受更多选项。请参阅man手册以获取详细信息。
如果路径元素的数量不是恒定的,您可能需要不同的解决方案。例如:https://stackoverflow.com/q/3832068/10971581
英文:
If the number of path elements is constant and each line has the same number of them, then sort
alone can do this.
In your example, each line contains 6 path elements delimited by /
(lines start with an empty element).
You seem to want to sort by element 6 and then sub-sort on element 5, both numerically.
So:
sort -t/ -n -k6,6 -k5,5 inputfile
The -k
can take more options. See manpage for details.
If the number of path elements is not constant, you may need a different solution. For example: https://stackoverflow.com/q/3832068/10971581
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论