如何在 Bash 中的分隔符上拆分字符串? [英] How do I split a string on a delimiter in Bash?

查看:25
本文介绍了如何在 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"

我不一定需要 ADDR1ADDR2 变量.如果它们是数组的元素,那就更好了.

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="bla@some.com;john@home.com"

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

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

输出:

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

有一个解决方案涉及将 Internal_field_separator (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="bla@some.com;john@home.com"

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

IFS=$OIFS

顺便说一句,当我尝试

mails2=($IN)

在循环打印时我只得到第一个字符串,$IN 周围没有括号它可以工作.

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

推荐答案

您可以设置内部字段分隔符 (IFS) 变量,然后让它解析成一个数组.当这种情况发生在一个命令中时,对 IFS 的分配只会发生在该单个命令的环境中(到 read ).然后它根据 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.

这个例子将解析由 ; 分隔的一行项目,将其推入一个数组:

This example will parse one line of items separated by ;, pushing it into an array:

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

另一个例子是处理$IN的全部内容,每次输入一行以分隔;:

This other example is for processing the whole content 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"

这篇关于如何在 Bash 中的分隔符上拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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