本文介绍了Bash字符串与IFS进行数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用IFS将字符串转换为数组时遇到麻烦.这是我的字符串:

I'm having trouble using the IFS to convert my string into an array. Here is what I have as my string:

"Jun01 Jun02 Jun03 Jun04 Jun05 ..." #in that format, separated by spaces

这是我尝试过的代码:

IFS=" " #set it to space character
DATES_ARRAY=($DATES_STRING) #from above
echo ${DATES_ARRAY[0]} #output is empty

但是,当我删除I​​FS行时,它会起作用.但是我用了几行来打印出它的默认ASCII值,然后我得到了'32',这意味着'Space'字符.作为OCD程序员,我想为自己设置安全性……我不知道如何预先设置它!

However when I remove the IFS line it works. But I used a few lines to print out its default ASCII value and I got '32' which means 'Space' character. Being an OCD programmer I'd like to set it myself just to be safe... I don't know how it's going to be preset a priori!

那么为什么尝试将IFS手动设置为Space无效?

So why does trying to set IFS to Space manually not work?

推荐答案

它确实可以工作,但是由于在默认情况下可以保证IFS中存在空间,因此它还是不必要的.不要手动设置.这样做可能会引起问题.

It does work, but it's unnecessary anyway because space is guaranteed to be in IFS by default. Don't set it manually. Doing so can cause problems.

基本上,切勿在Bash中使用分词.有时,如果使用得很仔细,则需要咬住子弹并在仅限于POSIX sh的情况下使用.如果要设置IFS,请在少数对它起作用的命令之一(或最多在局部于某个函数中)的环境中进行设置.

Basically, never use word-splitting in Bash. Sometimes it's required to bite the bullet and use it if restricted to POSIX sh, if used very carefully. If you're going to set IFS, set it in the environment of one of the few commands where it has some effect, or at the very most, locally to a function.

您将永远不需要使用它,因此我将不解释所有内容:

You'll never need to use this so I won't explain everything:

$ printf -v str '%s ' Jun{01..10}
$ set -f
$ IFS=' ' declare -a 'arr=($str)'
$ declare -p arr
declare -a arr='([0]="Jun01" [1]="Jun02" [2]="Jun03" [3]="Jun04" [4]="Jun05" [5]="Jun06" [6]="Jun07" [7]="Jun08" [8]="Jun09" [9]="Jun10")'

IFS在此处多余地设置了空格以表明其有效.

IFS set to space here redundantly to show it works.

从字符串到数组的最正确方法可能是使用read.许多示例此处.

Probably the most correct way to go from a string to an array is to use read. Many examples here.

规范的方法是:

read -ra arr <<<"$str"

read环境中可以选择设置IFS以用作分隔符(如果不是空格的话).

where IFS is optionally set in the environment of read to act as a delimiter if it's something other than whitespace.

这篇关于Bash字符串与IFS进行数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:55
查看更多