使用 find 从 bash 脚本中递归获取文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14938830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:35:46  来源:igfitidea点击:

Get the filename from bash script recursively using find

bashdirectory-traversal

提问by RameshVel

I am trying retrieve the filename from the find command recursively. This command prints all the filenames with full path

我正在尝试从 find 命令中递归检索文件名。此命令打印所有带有完整路径的文件名

> for f in $(find -name '*.png'); do echo "$f";done          
> ./x.png
> ./bg.png
> ./s/bg.png

But when i try to just get the name of the file using these commands, it prints

但是当我尝试使用这些命令获取文件名时,它会打印

for f in $(find -name '*.png'); do echo "${f##*/}";done                                                                                                       
bg.png

and

for f in $(find -name '*.png'); do echo $(basename $f);done   
bg.png

It omits other 2 files. I am new to shell scripting. I couln't figure out whats wrong with this one.

它省略了其他 2 个文件。我是 shell 脚本的新手。我想不通这个有什么问题。

EDIT:

编辑:

THis is what i have actually wanted.

这就是我真正想要的。

  1. I want to loop through a directory recursively and find all png images
  2. send it to pngnq for RGBA compression
  3. It outputs the new file with orgfilename-nq8.png
  4. send it to pngcrush and rename and generate a new file (org file will be overwritten )
  5. remove new file
  1. 我想递归遍历目录并找到所有 png 图像
  2. 将其发送到 pngnq 进行 RGBA 压缩
  3. 它输出新文件 orgfilename-nq8.png
  4. 将它发送到 pngcrush 并重命名并生成一个新文件(组织文件将被覆盖)
  5. 删除新文件

i have a code which works on a single directory

我有一个适用于单个目录的代码

for f in *.png; do pngnq -f -n 256 "$f" && pngcrush "${f%.*}"-nq8.png "$f";rm "${f%.*}"-nq8.png; done

I want to do this recursively

我想递归地做到这一点

回答by Gilles Quenot

Simply do :

简单地做:

find -name '*.png' -printf '%f\n'

If you want to run something for each files :

如果你想为每个文件运行一些东西:

find -name '*.png' -printf '%f\n' |
while read file; do
    # do something with "$file"
done 

Or with xargs:

或与xargs

find -name '*.png' -printf '%f\n' | xargs -n1 command

Be sure you cannot use finddirectly like this :

确保您不能find像这样直接使用:

find -name '*.png' -exec command {} +

or

或者

find -name '*.png' -exec bash -c 'do_something with ${1##*/}' -- {} \;

Search -printfon http://unixhelp.ed.ac.uk/CGI/man-cgi?findor in

-printfhttp://unixhelp.ed.ac.uk/CGI/man-cgi?find 上搜索或在

man find | less +/^' *-printf'