在Linux命令行中以相对于当前目录的路径递归列出文件列表

254

这与这个问题类似,但我想在Unix中包括相对于当前目录的路径。如果我执行以下操作:

ls -LR | grep .txt

它不包括完整路径。例如,我有以下目录结构:

test1/file.txt
test2/file1.txt
test2/file2.txt

上述代码将返回:

file.txt
file1.txt
file2.txt

如何使用标准Unix命令,使它包含相对于当前目录的路径?


7
这只是表明ls缺少这个功能。 - Arjun Singri
1
很遗憾,所有这些解决方案都需要使用“find”或“tree”。我正在通过ssh连接到一个安卓设备,似乎只有“ls”,没有这些其他工具 :/ - Ponkadoodle
14个回答

1
你可以创建一个 shell 函数,例如在你的 .zshrc.bashrc 文件中:
filepath() {
    echo $PWD/$1
}

filepath2() {
    for i in $@; do
        echo $PWD/$i
    done
}

第一个显然只适用于单个文件。


1
如果你想在输出中保留类似文件大小等ls的细节,那么这应该可以工作。
sed "s|<OLDPATH>|<NEWPATH>|g" input_file > output_file

0
在我的情况下,使用tree命令
相对路径
tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\./.*' | while read file; do
  echo $file
done

绝对路径

tree -ifF ./dir | grep -v '^./dir$' | grep -v '.*/$' | grep '\./.*' | while read file; do
  echo $file | sed -e "s|^.|$PWD|g"
done

0
您可以像这样实现此功能:
首先,使用ls命令指向目标目录。然后使用find命令过滤结果。 从您的情况来看,似乎文件名始终以一个单词开头file***.txt
ls /some/path/here | find . -name 'file*.txt'   (* represents some wild card search)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接