本文介绍了我怎么拆就猛砸分隔符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何分割字符串根据Bash的分隔符?

How do I split a string based on a delimiter in Bash?

我有这个字符串存储在一个变量:

I have this string stored in a variable:

IN="[email protected];[email protected]"

现在我想通过来分割字符串; 分隔符,这样我有:

Now I would like to split the strings by ; delimiter so that I have:

ADDR1="[email protected]"
ADDR2="[email protected]"

我不一定需要 ADDR1 ADDR2 变量。如果他们是一个数组,甚至更好的元素。

I don't necessarily need the ADDR1 and ADDR2 variables. 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="[email protected];[email protected]"

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

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

输出:

> [[email protected]]
> [[email protected]]

有是涉及设置(IFS)的解决方案; 。我不知道与答案发生了什么,你怎么重置 IFS 恢复为默认?

There was a solution involving setting Internal_field_separator (IFS) to ;. I am not sure what happened with that answer, how do you reset IFS back to default?

RE: IFS 的解决方案,我想这和它的作品,我把旧的 IFS ,然后将其还原

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

IN="[email protected];[email protected]"

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

IFS=$OIFS

顺便说一句,当我试图

BTW, when I tried

mails2=($IN)

我只在循环打印时,它得到了第一个字符串,没有括号 $ IN 它的工作原理。

推荐答案

您可以设置(IFS )变量,然后让它解析成一个数组。当这种情况发生在一个命令,然后分配到 IFS 仅发生于单个命令的环境(为) 。然后,它解析根据 IFS 变量值输入到一个数组,然后我们可以遍历。

You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to IFS only takes place to that single command's environment (to read ). It then parses the input according to the IFS variable value into an array, which we can then iterate over.

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

这将解析由分离项目之一线; ,将它推到一个数组。工具和处理全 $ IN ,由输入分隔每次一行;

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 ;:

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

这篇关于我怎么拆就猛砸分隔符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:43