按日期顺序列出文件,文件名中带有空格 [英] Listing files in date order with spaces in filenames

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

问题描述

我从一个文件开始,该文件包含以随机顺序排列的数百个文件(完整路径)的列表.我想在该列表中列出十个最新文件的详细信息.这是我天真的尝试:

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

我曾尝试引用原始文件列表文件中的文件,但是here-document仍将文件拆分为文件名中的空格,将引号视为文件名的一部分:

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

但是,我认为这段代码不会比执行循环更有效.另外,如果list-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天全站免登陆