【发布时间】:2013-10-31 09:53:55
【问题描述】:
我有一些问题 - 我有一个带有目录的文件列表(在 .txt 文件中),即:/student/2012/my/Video/hello.php。我需要做的是获取该列表的最后编辑文件,但我不知道如何做到这一点..
谢谢
【问题讨论】:
标签: linux bash file list shell
我有一些问题 - 我有一个带有目录的文件列表(在 .txt 文件中),即:/student/2012/my/Video/hello.php。我需要做的是获取该列表的最后编辑文件,但我不知道如何做到这一点..
谢谢
【问题讨论】:
标签: linux bash file list shell
你可以说:
ls -1tr $(cat filename.txt) | tail -1
为了从filename.txt 中包含的文件中获取最近编辑的文件。
【讨论】:
-1rt;您可能选择了较早的版本,上面写着-lrt。使用1(数字一)代替字母l。
在this answer 中,我演示了 bash 中的快速排序算法。这是sn-p:
quicksort_files_by_mod_date() {
if ((!$#)); then
qs_ret=()
return
fi
# the return array is qs_ret
local first=$1
shift
local newers=()
local olders=()
qs_ret=()
for i in "$@"; do
if [[ $i -nt $first ]]; then
newers+=( "$i" )
else
olders+=( "$i" )
fi
done
quicksort_files_by_mod_date "${newers[@]}"
newers=( "${qs_ret[@]}" )
quicksort_files_by_mod_date "${olders[@]}"
olders=( "${qs_ret[@]}" )
qs_ret=( "${newers[@]}" "$first" "${olders[@]}" )
}
然后,您可以将文件的内容 slurp 到一个数组中,并使用此函数获取一个包含已排序文件名的数组qs_ret,然后您将打印第一个:
mapfile -t array < files.txt
quicksort_files_by_mod_date "${array[@]}"
echo "${qs_ret[0]}"
:)
备注。这都是 100% 的 bash! (并使用一些 bashisms)。
备注。这也适用于包含空格的文件名! (当然不是换行符)。
备注。没有检查files.txt中的文件是否存在!
当然,如果您只想要最新的,则不需要快速排序。应该这样做:
recent=
while IFS= read -r file; do
[[ $file -nt $recent ]] && recent=$file
done < files.txt
echo "$recent"
嘿,它仍然是 100% bash,并且不会因文件名包含空格而失败。
【讨论】: