庆典:上市日期顺序文件,文件名中使用空格 [英] bash: listing files in date order, with spaces in filenames

查看:141
本文介绍了庆典:上市日期顺序文件,文件名中使用空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始用含有数百随机顺序文件(全路径)的列表的文件。我想列出在该列表中的十个最新的文件的细节。这是我的幼稚的尝试:

I am starting with a file containing a list of hundreds of files (full paths) in a random order. I would like to list the details of the ten latest files in that list. This is my naive attempt:

$ ls -las -t `cat list-of-files.txt` | head -10

这样的作品,只要没有文件有空格,但如果他们这样做的这些文件是在空间分割和单独的文件处理失败。文件的Hello World给我:

That works, so long as none of the files have spaces in, but fails if they do as those files are split up at the spaces and treated as separate files. File "hello world" gives me:

ls: hello: No such file or directory
ls: world: No such file or directory

我曾尝试在列表的的档案原始文件引用了文件,但在这里,文件还分割了的文件在文件名的空间,处理引号作为文件名的一部分:

I have tried quoting the files in the original list-of-files file, but the here-document still splits the files up at the spaces in the filenames, treating the quotes as part of the filenames:

$ ls -las -t `awk '{print "\"" $0 "\""}' list-of-files.txt` | head -10

ls: "hello: No such file or directory
ls: world": No such file or directory

我能想到这样做的唯一办法,是单独LS每个文件(使用xargs的可能),并创建一个文件列表的中间文件并在各行中排序顺序的第一个字段的日期,然后排序这中间文件。但是,感觉有点麻烦且低效的(数百的ls命令,而不是一个或两个)。但是,这可能是做到这一点的唯一途径?

The only way I can think of doing this, is to ls each file individually (using xargs perhaps) and create an intermediate file with the file listings and the date in a sortable order as the first field in each line, then sort that intermediate file. However, that feels a bit cumbersome and inefficient (hundreds of ls commands rather than one or two). But that may be the only way to do it?

有没有办法通过LS要处理的文件,在这些文件可能包含空间的列表 - 它似乎应该是简单的,但我很为难。

Is there any way to pass "ls" a list of files to process, where those files could contain spaces - it seems like it should be simple, but I'm stumped.

推荐答案

,你可以强制bash使用另一个字段分隔符:

Instead of "one or more blank characters", you can force bash to use another field separator:

OIFS=$IFS
IFS=$'\n'

ls -las -t $(cat list-of-files.txt) | head -10
IFS=$OIFS

不过,我不认为这code会比做一个循环效率更高;另外,如果文件在列表-OF-files.txt数超过参数的最大数量,将无法正常工作。

However, I don't think this code would be more efficient than doing a loop; in addition, that won't work if the number of files in list-of-files.txt exceeds the max number of arguments.

这篇关于庆典:上市日期顺序文件,文件名中使用空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆