
[英]Linux: How to list all files recursively with path relative to the current path, and do not include current path
[英]List files recursively in Linux CLI with path relative to the current directory
这类似于这个问题,但我想包括相对于 unix 中当前目录的路径。 如果我执行以下操作:
ls -LR | grep .txt
它不包括完整路径。 例如,我有以下目录结构:
test1/file.txt
test2/file1.txt
test2/file2.txt
上面的代码将返回:
file.txt
file1.txt
file2.txt
如何使用标准 Unix 命令让它包含相对于当前目录的路径?
使用查找:
find . -name \*.txt -print
在使用 GNU find 的系统上,像大多数 GNU/Linux 发行版一样,您可以省略 -print。
使用带有-f
(完整路径)和-i
(无缩进)的tree
:
tree -if --noreport .
tree -if --noreport directory/
然后您可以使用grep
过滤掉您想要的那些。
如果找不到命令,可以安装:
键入以下命令在 RHEL/CentOS 和 Fedora linux 上安装 tree 命令:
# yum install tree -y
如果您使用的是 Debian/Ubuntu,Mint Linux 在您的终端中输入以下命令:
$ sudo apt-get install tree -y
尝试find
。 您可以在手册页中准确查找它,但它有点像这样:
find [start directory] -name [what to find]
所以对于你的例子
find . -name "*.txt"
应该给你你想要的。
您可以使用 find 代替:
find . -name '*.txt'
这就是诀窍:
ls -R1 $PWD | while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done | grep -i ".txt"
但是它通过解析ls
这一点,但是,GNU 和 Ghostscript 社区认为这是不好的形式。
DIR=your_path
find $DIR | sed 's:""$DIR""::'
'sed' 将从所有 'find' 结果中删除 'your_path'。 并且您收到相对于“DIR”路径。
要使用 find 命令获取所需文件的实际完整路径文件名,请将其与 pwd 命令一起使用:
find $(pwd) -name \*.txt -print
从根目录“/”开始搜索,在文件系统上找到名为“filename”的文件。 “文件名”
find / -name "filename"
这是一个 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
如果你想在你的输出中保留 ls 的细节,比如文件大小等,那么这应该可以工作。
sed "s|<OLDPATH>|<NEWPATH>|g" input_file > output_file
您可以创建一个 shell 函数,例如在您的.zshrc
或.bashrc
:
filepath() {
echo $PWD/$1
}
filepath2() {
for i in $@; do
echo $PWD/$i
done
}
显然,第一个只适用于单个文件。
您可以像这样实现此功能
首先,使用 ls 命令指向目标目录。 稍后使用 find 命令从中过滤结果。 从您的情况来看,这听起来像是 - 文件名始终以单词file***.txt
开头
ls /some/path/here | find . -name 'file*.txt' (* represents some wild card search)
在我的情况下,使用 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.