如何在shell脚本中获取目录中的文件列表?
我正在尝试使用 shell 脚本获取目录的内容。
我的脚本是:
for entry in `ls $search_dir`; do
echo $entry
done
其中 $search_dir
是相对路径。但是,$search_dir
包含许多名称中带有空格的文件。在这种情况下,该脚本不会按预期运行。
我知道我可以使用 输入 *
,但这仅适用于我当前的目录。
我知道我可以更改到该目录,使用 输入 *
然后再更改回来,但我的特殊情况不允许我这样做。
我有两个相对路径 $search_dir
和 $work_dir
,我必须同时处理这两个路径,读取它们,在其中创建/删除文件等。
那么我现在该怎么办?
PS:我用bash。
I'm trying to get the contents of a directory using shell script.
My script is:
for entry in `ls $search_dir`; do
echo $entry
done
where $search_dir
is a relative path. However, $search_dir
contains many files with whitespaces in their names. In that case, this script does not run as expected.
I know I could use for entry in *
, but that would only work for my current directory.
I know I can change to that directory, use for entry in *
then change back, but my particular situation prevents me from doing that.
I have two relative paths $search_dir
and $work_dir
, and I have to work on both simultaneously, reading them creating/deleting files in them etc.
So what do I do now?
PS: I use bash.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
这是一种语法对我来说更容易理解的方法:
./
是当前工作目录,但可以替换为任何路径*.txt
返回任何内容.txt您可以通过直接在终端中输入
ls
命令来轻松检查将列出的内容。基本上,您创建一个变量
yourfilenames
,其中包含 list 命令作为单独元素返回的所有内容,然后循环遍历它。该循环创建一个临时变量eachfile
,其中包含循环通过的变量的单个元素,在本例中是文件名。这不一定比其他答案更好,但我发现它很直观,因为我已经熟悉 ls 命令和 for 循环语法。This is a way to do it where the syntax is simpler for me to understand:
./
is the current working directory but could be replaced with any path*.txt
returns anything.txtYou can check what will be listed easily by typing the
ls
command straight into the terminal.Basically, you create a variable
yourfilenames
containing everything the list command returns as a separate element, and then you loop through it. The loop creates a temporary variableeachfile
that contains a single element of the variable it's looping through, in this case a filename. This isn't necessarily better than the other answers, but I find it intuitive because I'm already familiar with thels
command and the for loop syntax.这里的其他答案很好,回答了你的问题,但这是“bash获取目录中的文件列表”的最高谷歌结果(我正在寻找它来保存文件列表),所以我想我会发布一个该问题的答案:
如果您只想要某种类型(例如任何 .txt 文件):
请注意 $search_path 是可选的; ls> filename.txt 将执行当前目录。
The other answers on here are great and answer your question, but this is the top google result for "bash get list of files in directory", (which I was looking for to save a list of files) so I thought I would post an answer to that problem:
If you want only a certain type (e.g. any .txt files):
Note that $search_path is optional; ls > filename.txt will do the current directory.
变体
注释:
.
:当前文件夹-maxdepth 1
以递归搜索-type f :查找文件,而不是目录 (
d
)-not -path '*/\.*'
:不返回.hidden_files
./
Variations
Notes:
.
: current folder-maxdepth 1
to search recursively-type f
: find files, not directories (d
)-not -path '*/\.*'
: do not return.hidden_files
sed 's/^\.\///g'
: remove the prepended./
from the result list类似于接受的答案 - 但仅列出文件名而不是完整路径:
这似乎已经在不久前得到回答,但我想我也想贡献一个答案,仅列出所需的文件目录,而不是完整路径。
参考资料:
有关 IFS 的更多信息,请参见 此处。
有关在 shell 中查找子字符串的更多信息,请参阅 此处。
\n' #for in $() splits based on IFS search_dir="$(pwd)" for entry in $(ls $search_dir) do echo $entry done如果您还想过滤特定文件,您可以添加一个
grep -q
语句。参考资料:
有关 IFS 的更多信息,请参见 此处。
有关在 shell 中查找子字符串的更多信息,请参阅 此处。
Similar to Accepted answer - but lists only file names instead of full paths:
This seems to have been answered a while ago, but I guess I want to also contribute an answer that just lists the files in the desired directory, as opposed to the full paths.
References:
More information about IFS can be found here.
More information about finding substrings in shell can be found here.
\n' #for in $() splits based on IFS search_dir="$(pwd)" for entry in $(ls $search_dir) do echo $entry doneIf you also wanted to filter for a specific file you would add a
grep -q
statement.References:
More information about IFS can be found here.
More information about finding substrings in shell can be found here.
接受的答案不会返回带有“
.
”前缀的文件要做到这一点,请使用
The accepted answer will not return files prefix with a '
.
'To do that use
除了@Ignacio Vazquez-Abrams 得到最多支持的答案之外,还可以考虑以下解决方案,这些解决方案也都有效,具体取决于你想做什么。请注意,您可以将
"path/to/some/dir"
替换为.
,以便在当前目录中搜索。1. 列出不同的使用
find
和ls
的文件类型参考:
find
,请参阅 这个答案。另请参阅我的评论。ls
,请参阅 linuxhandbook.com:如何仅列出 Linux 中的目录< /a>提示:对于下面的任何
find
示例,如果您希望对其进行排序,可以将输出通过管道传输到sort -V
。示例:
仅列出常规文件(
-type f
)1 级深度:仅列出符号链接 (
-type l
) 1 级深:仅列出目录 (
-type d
) 1 级深:< /strong>请注意,对于此处的
find
示例,我们还添加了-mindepth 1
以排除当前目录.
,这将否则将在目录列表的顶部打印为.
。请参阅此处:如何从查找“type d”中排除此/当前/点文件夹结合上面的一些内容:仅列出常规文件和符号链接(
-type f,l
)1层深:使用逗号(
,
) 来分隔-type
的参数:2. 将任何命令的输出捕获到 bash 索引数组中,其中元素由换行符分隔 (
\n)
这是通过告诉 bash 根据换行符
\n
而不是空格字符分隔字符串中的元素来解决的 - 这是默认的IFS
(内部字段分隔符 - -参见 Bash 脚本中IFS
的含义 ) bash 使用的变量。为此,我建议使用mapfile
命令。每当您想要将字符串读入 bash 数组时,名为
shellscript
的 bash 脚本静态代码分析工具建议使用mapfile
或read -r
,基于换行符 (\n
) 分隔元素。请参阅:https://github.com/koalaman/shellcheck/wiki/SC2206。更新:要查看如何使用
mapfile
和read -r
执行此操作的示例,请参阅我的答案:如何将多行字符串读入常规 bash“索引”数组。 我现在更喜欢使用read -r
而不是mapfile
,因为mapfile
会将任何空行保留为数组中的元素,如果任何存在,这是我不想要的,而read -r
[再次,我现在的偏好]不会将空行保留为数组中的元素。(回到我原来的答案:)
以下是如何使用
mapfile
命令将换行符分隔的字符串转换为常规 bash“索引”数组。注意:
ls -1
(即“破折号数字_one”)将每个文件名放在自己的行上,从而通过换行符\n
字符将它们分开。<<<
在 bash 中称为“此处字符串”。mapfile --help
或help mapfile
获取帮助。完整代码示例:
来自文件array_list_all_files_and_directories.sh 在我的 eRCaGuy_hello_world 存储库中:
这是上面运行的代码块的示例输出在我的 eRCaGuy_hello_world/python 目录内/github.com/ElectricRCAaircraftGuy/eRCaGuy_hello_world" rel="nofollow noreferrer">eRCaGuy_hello_world 仓库:
In addition to the most-upvoted answer by @Ignacio Vazquez-Abrams, consider the following solutions which also all work, depending on what you are trying to do. Note that you can replace
"path/to/some/dir"
with.
in order to search in the current directory.1. List different types of files using
find
andls
References:
find
, see this answer. See also my comment here.ls
, see linuxhandbook.com: How to List Only Directories in LinuxTip: for any of the
find
examples below, you can pipe the output tosort -V
if you'd like it sorted.Example:
List only regular files (
-type f
) 1 level deep:List only symbolic links (
-type l
) 1 level deep:List only directories (
-type d
) 1 level deep:Note that for the
find
example here, we also add-mindepth 1
in order to exclude the current directory,.
, which would be printed as.
at the top of the directory list otherwise. See here: How to exclude this / current / dot folder from find "type d"Combine some of the above: list only regular files and symbolic links (
-type f,l
) 1 level deep:Use a comma (
,
) to separate arguments to-type
:2. Capture the output of any command into a bash indexed array, with elements separated by the newline char (
\n
)This is solved by telling bash to separate elements in the string based on the newline char
\n
instead of the space char--which is the defaultIFS
(Internal Field Separator--see The Meaning ofIFS
in Bash Scripting) variable used by bash. To do this, I recommend using themapfile
command.The bash script static code analyzer tool named
shellscript
recommends usingmapfile
orread -r
whenever you want to read in a string into a bash array, separating elements based on the newline char (\n
). See: https://github.com/koalaman/shellcheck/wiki/SC2206.Update: to see examples of how to do this with both
mapfile
andread -r
see my answer here: How to read a multi-line string into a regular bash "indexed" array. I now prefer to useread -r
instead ofmapfile
, becausemapfile
will KEEP any empty lines as elements in the array, if any exist, which I do NOT want, whereasread -r
[again, my preference now] will NOT keep empty lines as elements in the array.(Back to my original answer:)
Here is how to convert a newline-separated string into a regular bash "indexed" array with the
mapfile
command.Notes:
ls -1
(that's a "dash numeral_one") in order to put each filename on its own line, thereby separating them all by the newline\n
char.<<<
is called a "here string" in bash.mapfile --help
, orhelp mapfile
, for help.Full code example:
From file array_list_all_files_and_directories.sh in my eRCaGuy_hello_world repo:
Here is the example output of the code block just above being run inside the eRCaGuy_hello_world/python dir of my eRCaGuy_hello_world repo:
获取
shell
和bash
目录中的文件列表,4 个技巧一些备注
$search_dir
为空或者$search_dir
不存在。数组
,globstar
用于递归而不是find
。Posix
shell
首先:如果您
(注意使用引号,以在路径名中保留空格)
从那里开始,即使
所以下一步必须:
现在
bash
。bash
array我经常使用这个:
但是,同样的评论:这将产生一个包含
("/the/path to/base/dir/*") 的数组
如果没有文件或路径错误。您可以使用以下命令清除第一个错误的字段
或者您可以对数组进行快速循环,请参见此答案的底部...
然后
使用 bash 数组,您可以使用完整的内容显示数组的内容路径,作者:
并且,仅显示文件名:
使用 globstar 进行递归:
来自
man bash
:默认情况下,
globstar
处于关闭状态:然后
将打印
$search_dir/
下的每个条目。搜索文件。
快速循环数组以删除不是文件的条目。
然后
将打印
$search_dir/
下的每个文件。搜索文件时构建数组
如果您的
$search_dir
确实包含大量非文件条目,则最好从测试的条目构建数组:Get list of files in a directory in
shell
and inbash
, 4 tipsSome remarks
$search_dir
is empty or if$search_dir
doesn't exist.arrays
,globstar
for recursivity instead offind
.Posix
shell
first:If you
(note the use of quote, for keeping space in path name)
From there, script execution will continue even if
So next step have to be:
Now
bash
.bash
arrayI often use this:
But, same remark: this will produce an array containing
("/the/path to/base/dir/*")
in case of no file or wrong path.You could clean 1st wrong field by using
Or you could do a quick loop over the array, see at bottom of this answer...
Then
With bash array, you could show the content of your array with full path, by:
And, for showing only file names:
Recursion using globstar:
From
man bash
:globstar
is off by default:Then
will print every entries under
$search_dir/
.Searching for files.
Quick loop over array for dropping entries which are not files.
Then
will print every files under
$search_dir/
.Building array while searching for files
If your
$search_dir
do hold a lot of non-file entries, you'd better build array from tested entries:这是列出目录中文件的另一种方法(使用不同的工具,不如其他一些答案那么有效)。
echo *
输出当前目录的所有文件。for
循环迭代每个文件名并打印到标准输出。此外,如果在目录中查找目录,请将其放入
for
循环中:test -d
检查文件是否是目录。Here's another way of listing files inside a directory (using a different tool, not as efficient as some of the other answers).
echo *
Outputs all files of the current directory. Thefor
loop iterates over each file name and prints to stdout.Additionally, If looking for directories inside the directory then place this inside the
for
loop:test -d
checks if the file is a directory.使用映射文件有更简单的答案!
然后您可以使用
file_list
列出some_path
中的所有内容!如果您只想要文件列表,请使用
find
而不是ls
Ex)
There is simpler answer with using mapfile!
Then you can use
file_list
list with all contents insome_path
!If you want just file list, use
find
instead ofls
Ex)
如果您已经安装了
tree
工具或者可以安装它,那么它是一个非常好的工具。它可以列出指定目录及其子目录中的所有文件。还可以通过多种方式过滤输出:等等。只需
tree --help
即可获取更多信息。If you have installed the
tree
tool or can install it, it's a pretty good tool. It can list all the files in the specified dir and its subdir. Also can filter the output in many ways:etc. Just
tree --help
for more info.