Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash &引用;查找“;带有变量目录的命令_Bash_Variables_Find - Fatal编程技术网

Bash &引用;查找“;带有变量目录的命令

Bash &引用;查找“;带有变量目录的命令,bash,variables,find,Bash,Variables,Find,我试图列出由变量DIR给出的目录中的文件。到目前为止,我的代码如下所示: for i in `find $DIR -name "*.txt" 变量DIR已定义。我不确定这里的语法是什么 ls "${DIR}/*.txt" 或 我们应该做到这一点。第一个只列出目录本身中的*.txt文件,第二个也列出子目录中的*.txt文件。不确定您想要什么 find $DIR -name "*.txt" -print 将列出以.txt结尾并位于$DIR或其子目录中的所有文件。您可以省略-print,因为这是

我试图列出由变量
DIR
给出的目录中的文件。到目前为止,我的代码如下所示:

for i in `find $DIR -name "*.txt"
变量
DIR
已定义。我不确定这里的语法是什么

ls "${DIR}/*.txt"


我们应该做到这一点。第一个只列出目录本身中的
*.txt
文件,第二个也列出子目录中的
*.txt
文件。

不确定您想要什么

find $DIR -name "*.txt" -print
将列出以
.txt
结尾并位于
$DIR
或其子目录中的所有文件。您可以省略
-print
,因为这是默认行为

如果您想对该文件执行简单的操作,可以使用
find
-exec
功能:

find $DIR -name "*.txt" -exec wc -l {} \;
也可以使用循环:

for f in `find $DIR -name "*.txt"`; do
    wc -l $f
    mv $f /some/other/dir/
fi
注意:正如@mauro有益地指出的,如果
目录或文件名包含空格,这将不起作用


干杯

我想您想对
$DIR
和/或其子目录下扩展名为“txt”的所有文件执行给定操作。像往常一样,有不同的解决方案

这个:

$ for i in $(find "$DIR" -name \*.txt) ; do echo "Do something with ${i}" ; done
如果文件路径(文件本身或一个子目录)包含空格,将不起作用

但是你可以用这个:

$ find "$DIR" -type f -name \*.txt | while read i ; do echo "Do something with ${i}" ; done
或者这个:

$ find "$DIR" -type f -name \*.txt -print0 | xargs -0 -I {} echo "Do something with {}"
$ find "$DIR" -type f -name \*.txt -exec echo "Do something with {}" \;
或者这个:

$ find "$DIR" -type f -name \*.txt -print0 | xargs -0 -I {} echo "Do something with {}"
$ find "$DIR" -type f -name \*.txt -exec echo "Do something with {}" \;

或者。。。100个附加解决方案。

为什么不
ls“$DIR”
?我还需要包括.txt部分,因为我只查看.txt文件。你对
$DIR
子目录中的文件感兴趣,还是只对
$DIR
本身感兴趣?该死,我以为我给出了一个全面的答案,却忘了
ls${DIR}/*.txt
…如果文件路径包含一个或多个空格,则循环解决方案将不起作用。您是对的。我从不在文件或目录名中使用空格,所以我没有考虑它。我加了一张便条。(尽管我不知道这是否值得投反对票)。