将文件目录分配给一个变量

将文件目录分配给一个变量

我有一个包含近 400 个文件的目录,我想将所有 .txt 文件分配给我正在编写的 bash 脚本中的单个变量。但是我不太确定该怎么做。我纯粹对文件名本身感兴趣,而不是所述文件的内容。

答案1

如果您想要这些名称,最好将它们分配给一个数组。

names=( *.txt )

如果你想要内容的话

contents="$( cat *.txt )"

答案2

做这样的事情。此单行代码为文件夹.txt中的所有文件生成一个数组/root/tmpdir

[root@localhost ~]# export LIST=() ; for file in `find /root/tmpdir -name *.txt -exec readlink -e '{}' \;` ; do LIST+=($file) ; done
[root@localhost ~]# echo ${LIST[*]}
/root/tmpdir/newdir/file.txt /root/tmpdir/file.txt
[root@localhost ~]#

或者,您可以创建一个包含用 分隔的文件名的变量,

[root@localhost ~]# export LIST; for file in `find /root/tmpdir -name *.txt -exec readlink -e '{}' \;` ; do LIST=$LIST$file, ; done
[root@localhost ~]# echo $LIST
/root/tmpdir/newdir/file.txt,/root/tmpdir/file.txt,

聚苯乙烯

这两个示例都查找文件扩展名.txt而不是内容。另外,此查找是递归查找,您可以更改参数以使其仅在一个文件夹内搜索。

相关内容