Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

bash - 如何在Bash中的分隔符上拆分字符串?(How do I split a string on a delimiter in Bash?)

I have this string stored in a variable:

(我将此字符串存储在变量中:)

IN="bla@some.com;john@home.com"

Now I would like to split the strings by ;

(现在我想用拆分字符串;)

delimiter so that I have:

(分隔符,以便我有:)

ADDR1="bla@some.com"
ADDR2="john@home.com"

I don't necessarily need the ADDR1 and ADDR2 variables.

(我不一定需要ADDR1ADDR2变量。)

If they are elements of an array that's even better.

(如果它们是数组的元素,那就更好了。)


After suggestions from the answers below, I ended up with the following which is what I was after:

(经过以下答案的建议后,我得出了以下结论:)

#!/usr/bin/env bash

IN="bla@some.com;john@home.com"

mails=$(echo $IN | tr ";" "
")

for addr in $mails
do
    echo "> [$addr]"
done

Output:

(输出:)

> [bla@some.com]
> [john@home.com]

There was a solution involving setting Internal_field_separator (IFS) to ;

(解决方案涉及将Internal_field_separator (IFS)设置为;)

.

(。)

I am not sure what happened with that answer, how do you reset IFS back to default?

(我不确定该答案发生了什么,如何将IFS重置为默认值?)

RE: IFS solution, I tried this and it works, I keep the old IFS and then restore it:

(RE: IFS解决方案,我尝试过并且可以正常工作,我保留了旧的IFS ,然后将其还原:)

IN="bla@some.com;john@home.com"

OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
    echo "> [$x]"
done

IFS=$OIFS

BTW, when I tried

(顺便说一句,当我尝试)

mails2=($IN)

I only got the first string when printing it in loop, without brackets around $IN it works.

(在循环打印时,我只有第一个字符串,没有$IN括弧,它可以工作。)

  ask by stefanB translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set the internal field separator (IFS) variable, and then let it parse into an array.

(您可以设置内部字段分隔符 (IFS)变量,然后将其解析为数组。)

When this happens in a command, then the assignment to IFS only takes place to that single command's environment (to read ).

(当这在命令中发生时,则仅向该单个命令的环境分配IFS (以read )。)

It then parses the input according to the IFS variable value into an array, which we can then iterate over.

(然后,它根据IFS变量值将输入解析为一个数组,然后可以对其进行迭代。)

IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
    # process "$i"
done

It will parse one line of items separated by ;

(它将解析由;分隔的一行项目;)

, pushing it into an array.

(,将其推入数组。)

Stuff for processing whole of $IN , each time one line of input separated by ;

(用于处理整个$IN ,每次输入一行用分隔;)

:

(:)

 while IFS=';' read -ra ADDR; do
      for i in "${ADDR[@]}"; do
          # process "$i"
      done
 done <<< "$IN"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...