linux显示ls命令的第一个文件的头



我有一个文件夹,例如名为"folder"。它下面有50000个txt文件,例如"00001.txt、00002.txt等"。现在我想用一个命令行来显示"00001.txt"中的头10行。我已经尝试过:ls folder | head -1它将显示第一个的文件名:00001.txt但我想展示folder/00001.txt的内容那么,我如何做类似os.path.join(folder, xx)的事情并显示它的head -10呢?

更好的方法是根本不使用ls;请参阅为什么不应该解析ls的输出,以及相应的UNIX&Linux问题为什么不解析ls(以及该怎么做?(。

在带有数组的shell上,可以将glob放入数组中,并通过索引引用它所包含的项。

#!/usr/bin/env bash
#              ^^^^- bash, NOT sh; sh does not support arrays
# make array files contain entries like folder/0001.txt, folder/0002.txt, etc
files=( folder/* )  # note: if no files found, it will be files=( "folder/*" )
# make sure the first item in that array exists; if it does't, that means
# the glob failed to expand because no files matching the string exist.
if [[ -e ${files[0]} || -L ${files[0]} ]]; then
# file exists; pass the name to head
head -n 10 <"${files[0]}"
else
# file does not exist; spit out an error
echo "No files found in folder/" >&2
fi

如果你想要更多的控制,我可能会使用find。例如,要跳过目录,可以使用-type f谓词(与-maxdepth 1一起关闭递归(:

IFS= read -r -d '' file < <(find folder -maxdepth 1 -type f -print0 | sort -z)
head -10 -- "$file"

虽然很难理解你在问什么,但我认为这样的东西会起作用:

head -10 $(ls | head -1)

基本上,您从$(ls | head -1)获取文件,然后打印内容。

如果将ls命令调用为ls "$PWD"/folder,它将在输出中包含文件的绝对路径。

相关内容

最新更新