bash - 如何读取WIN PATH并将每个目录设置为数组

[英]bash - how to read WIN PATH and set each single directory in to array


PATH value is some WIN PATH (remark- $PATH should be inserted to XML file)

PATH值是一些WIN PATH(应该将remark- $ PATH插入到XML文件中)

example:

例:

 PATH="EMRA\ER1\C&W GU SEY\UR Dir"

OR

要么

 PATH="TRQ\nb vf\EMRA\ER1\C&W GU SEY\Last Dir" 

 etc ..... so on

my target is to create bash script that count how many directories exists in the $PATH

我的目标是创建bash脚本,计算$ PATH中存在多少个目录

and set each directory in array

并在数组中设置每个目录

.

Let’s say that we want to print the directories names from the follwoing $PATH

假设我们要打印下面的$ PATH中的目录名称

PATH="EMRA\ER1\C&W GU SEY\UR Dir"

then we will get the following results

那么我们将得到以下结果

for ((i=0;i<=$Num_of_dir_in_path;i+=1))
do 

[[ ! -z  ${DIR[$i]}  ]] && echo ${DIR[$i]}  

done



EMRA
ER1
C&amp;W GU SEY
UR Dir

the problem is I not understand how to count the directories in the $PATH and how to set them in the array

问题是我不明白如何计算$ PATH中的目录以及如何在数组中设置它们

( its more difficult when directory include space )

(当目录包含空格时更难)

1 个解决方案

#1


2  

It looks like the paths are separated by a backslash, which means that you can read them into an array like this:

它看起来像是用反斜杠分隔的路径,这意味着你可以将它们读入这样的数组:

$ IFS='\' read -ra paths <<<"EMRA\ER1\C&amp;W GU SEY\UR Dir"
$ for path in "${paths[@]}"; do
>    echo "$path"
> done
EMRA
ER1
C&amp;W GU SEY
UR Dir

I would be careful using uppercase variable names in the shell. $PATH in particular is a very important internal variable!

我会小心在shell中使用大写变量名。 $ PATH特别是一个非常重要的内部变量!

As JID points out, if you only wanted to print the paths out, rather than do anything else in the loop, you could just use printf instead:

正如JID指出的那样,如果您只想打印出路径,而不是在循环中执行任何其他操作,则可以使用printf代替:

printf '%s\n' "${paths[@]}"

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2015/02/19/788ede8fd6998df469a0efaff51b5841.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号