使用&QUOT bash shell的列表文件;对于"循环 [英] Bash Shell list files using "for" loop

查看:105
本文介绍了使用&QUOT bash shell的列表文件;对于"循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的bash shell脚本递归列出当前目录下的名为.txt文件:

I use the following Bash Shell script to list the ".txt" files recursively under the current directory :

#!/bin/bash
for file in $( find . -type f -name "*.txt" )
do
  echo $file
  # Do something else.
done

然而,一些当前目录下的名为.txt文件中有空格在其名称,例如我testing.txt。上市损坏,例如我testing.txt被列为

However, some of the ".txt" files under the current directory have spaces in their names, e.g. "my testing.txt". The listing becomes corrupted, e.g. "my testing.txt" is listed as

my
testing.txt

看来,for循环使用空白(空格,\\ n等)来分隔文件列表中,但在我来说,我只想用\\ n来分隔的文件列表。

It seems that the "for" loop uses "white space" (space, \n etc) to separate the file list but in my case I want to use only "\n" to separate the file list.

有什么办法,我可以修改此脚本来实现这一目的。任何想法。

Is there any way I could modify this script to achieve this purpose. Any idea.

先谢谢了。

推荐答案

如果你正在使用bash 4,只使用一个水珠:

If you're using bash 4, just use a glob:

#!/bin/bash                                                                     

shopt -s globstar

for file in **/*.txt
do
  if [[ ! -f "$file" ]]
  then
      continue
  fi
  echo "$file"
  # Do something else.                                                          
done

请务必引用$文件,否则你会在其他地方有同样的问题。 ** 如果已启用将递归匹配的文件和目录 globstar

Be sure to quote "$file" or you'll have the same problem elsewhere. ** will recursively match files and directories if you have enabled globstar.

这篇关于使用&QUOT bash shell的列表文件;对于"循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆