在Linux CLI中以递归方式列出文件,其中包含相对于当前目录的路径

问题描述 投票:208回答:13

这类似于this question,但我想在unix中包含相对于当前目录的路径。如果我执行以下操作:

ls -LR | grep .txt

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

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

上面的代码将返回:

file.txt
file1.txt
file2.txt

如何使用标准Unix命令将其包含在相对于当前目录的路径中?

linux unix recursion ls
13个回答
289
投票

使用find:

find . -name \*.txt -print

在使用GNU find的系统上,与大多数GNU / Linux发行版一样,您可以省略-print。


1
投票

在文件系统上找到名为“filename”的文件,从根目录“/”开始搜索。 “文件名”

find / -name "filename" 

1
投票

如果你想在你的输出中保留详细信息,如文件大小等,那么这应该可行。

sed "s|<OLDPATH>|<NEWPATH>|g" input_file > output_file

0
投票

您可以像这样实现此功能 首先,使用ls命令指向目标目录。稍后使用find命令过滤掉它的结果。从你的情况来看,它听起来像 - 文件名始终以单词file***.txt开头

ls /some/path/here | find . -name 'file*.txt'   (* represents some wild card search)

0
投票

fish shell中,您可以执行此操作以递归列出所有pdf,包括当前目录中的pdf:

$ ls **pdf

如果你想要任何类型的文件,只需删除'pdf'。


70
投票

使用tree-f(完整路径)和-i(没有缩进线):

tree -if --noreport .
tree -if --noreport directory/

然后,您可以使用grep过滤掉您想要的那些。


如果找不到该命令,则可以安装它:

键入以下命令在RHEL / CentOS和Fedora linux上安装树命令:

# yum install tree -y

如果您使用的是Debian / Ubuntu,Mint Linux会在终端中输入以下命令:

$ sudo apt-get install tree -y

25
投票

试试find。您可以在手册页中查找它,但它有点像这样:

find [start directory] -name [what to find]

所以对你的例子

find . -name "*.txt"

应该给你你想要的东西。


9
投票

您可以使用find代替:

find . -name '*.txt'

5
投票

这样做的诀窍:

ls -R1 $PWD | while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done | grep -i ".txt"

但是,它通过对ls的解析进行“犯罪”来做到这一点,但这被GNU和Ghostscript社区视为不良形式。


4
投票
DIR=your_path
find $DIR | sed 's:""$DIR""::'

'sed'将从所有'find'结果中删除'your_path'。并且你接受了相对于'DIR'的路径。


4
投票

要使用find命令获取所需文件的实际完整路径文件名,请将其与pwd命令一起使用:

find $(pwd) -name \*.txt -print

1
投票

这是一个Perl脚本:

sub format_lines($)
{
    my $refonlines = shift;
    my @lines = @{$refonlines};
    my $tmppath = "-";

    foreach (@lines)
    {
        next if ($_ =~ /^\s+/);
        if ($_ =~ /(^\w+(\/\w*)*):/)
        {
            $tmppath = $1 if defined $1;    
            next;
        }
        print "$tmppath/$_";
    }
}

sub main()
{
        my @lines = ();

    while (<>) 
    {
        push (@lines, $_);
    }
    format_lines(\@lines);
}

main();

用法:

ls -LR | perl format_ls-LR.pl

1
投票

你可以创建一个shell函数,例如在你的.zshrc.bashrc

filepath() {
    echo $PWD/$1
}

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

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

© www.soinside.com 2019 - 2024. All rights reserved.