如何处理Bash中元素包含空格的数组? [英] How can I handle an array where elements contain spaces in Bash?

查看:119
本文介绍了如何处理Bash中元素包含空格的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 tmp.out 的文件,其中包含以下内容:

Let's say I have a file named tmp.out that contains the following:

c:\My files\testing\more files\stuff\test.exe
c:\testing\files here\less files\less stuff\mytest.exe

我想将该文件的内容放入数组,我这样做是这样的: / p>

I want to put the contents of that file into an array and I do it like so:

ARRAY=( `cat tmp.out` )

然后通过这样的for循环运行此

I then run this through a for loop like so

for i in ${ARRAY[@]};do echo ${i}; done

但是输出结果如下:

c:\My
files\testing\more
files\stuff\test.sas
c:\testing\files
here\less
files\less
stuff\mytest.sas

,我希望输出为:

c:\My files\testing\more files\stuff\test.exe
c:\testing\files here\less files\less stuff\mytest.exe

我该如何解决?

推荐答案

您可以使用IFS变量,内部字段分隔符。将其设置为空字符串以仅在换行符上分割内容:

You can use the IFS variable, the Internal Field Separator. Set it to empty string to split the contents on newlines only:

while IFS= read -r line ; do
    ARRAY+=("$line")
done < tmp.out

-r 保留原义的反斜杠。

这篇关于如何处理Bash中元素包含空格的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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