简体   繁体   English

在 Bash 中获取包含空格的文件名数组时出现问题

[英]Problem getting an array of filenames which contain whitespaces in Bash

I want to write a bash script and I need to get the filenames in a directory and I've done this:我想写一个 bash 脚本,我需要在一个目录中获取文件名,我已经这样做了:

list=`ls -p -m -1 $dir | grep -v /`
list=`echo $list | tr ' ' ','`
IFS=',' read -ra list_array <<< $list

If no file with whitespaces in the current directory exists, then the variable list_array holds the correct space-seperated array of filenames:如果当前目录中不存在带有空格的文件,则变量list_array包含正确的以空格分隔的文件名数组:

 $ echo "${list_array[*]}"
 a a.rar a.tar a.zip blah blah blah

But that wouldn't work correctly in situations where there exists some files with whitespaces in their names.To mitigate this, I changed that as follows:但这在存在一些名称中包含空格的文件的情况下无法正常工作。为了缓解这种情况,我将其更改如下:

list=`ls -p -m  $dir | grep -v /`     #This doesn't work in for filenames without whitespace
IFS=',' read -ra list_array <<< $list  

But now list_array only holds the name of the first file.但现在list_array只保存第一个文件的名称。

Any help is greatly appreciated.任何帮助是极大的赞赏。

You can use newlines as IFS.您可以使用换行符作为 IFS。

IFS=$'\n'
list_array=(`ls -p -m -1 . | grep -v /`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM