split 以分号分隔的单词

发布于 2024-12-22 07:27:49 字数 198 浏览 0 评论 0原文

这样的字符串,

我有一些像1;2;3;4;5

我希望能够迭代这个字符串,逐个获取每个单词。第一次迭代取 1,下一次迭代取 2,最后一次迭代取 5。

我想要这样的东西

for i in $(myVar)
do
echo $i
done

,但我不知道如何填充 myvar

I have some string like

1;2;3;4;5

I want to be able to iterate over this string taking each word one by one. For the first iteration to take 1 the next to take 2 and the last 5.

I want to have something like this

for i in $(myVar)
do
echo $i
done

but I do not know how to fill the myvar

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

把人绕傻吧 2024-12-29 07:27:49
echo '1;2;3;4;5' | tr \; \\n | while read line ; do echo $line; done
echo '1;2;3;4;5' | tr \; \\n | while read line ; do echo $line; done
红颜悴 2024-12-29 07:27:49

如果您仅为单个命令分配 IFS 变量,则无需备份它:

$ IFS=';' read -a words <<<"1;2;3;4;5"
$ for word in "${words[@]}"
do
    echo "$word"
done
1
2
3
4
5

其他有用的语法:

$ echo "${words[0]}"
1
$ echo "${words[@]: -1}"
5
$ echo "${words[@]}"
1 2 3 4 5

There's no need to back up the IFS variable if you assign it only for a single command:

$ IFS=';' read -a words <<<"1;2;3;4;5"
$ for word in "${words[@]}"
do
    echo "$word"
done
1
2
3
4
5

Other useful syntax:

$ echo "${words[0]}"
1
$ echo "${words[@]: -1}"
5
$ echo "${words[@]}"
1 2 3 4 5
述情 2024-12-29 07:27:49

也许最简单的方法是更改​​ IFS 环境变量:

OLDIFS="$IFS"
IFS=';'
for num in $a; do echo $num; done

# prints:
1
2
3
4
5

IFS="$OLDIFS"

记住之后将其更改回来,否则会发生奇怪的事情! :)

从 bash 手册页:

   IFS    The Internal Field Separator that is  used  for  word  splitting
          after  expansion  and  to  split  lines into words with the read
          builtin  command.   The  default  value  is  ``<space><tab><new-
          line>''.

Probably the easiest way to do this is change the IFS environment variable:

OLDIFS="$IFS"
IFS=';'
for num in $a; do echo $num; done

# prints:
1
2
3
4
5

IFS="$OLDIFS"

Remember to change it back afterwards or weird things will happen! :)

From the bash man page:

   IFS    The Internal Field Separator that is  used  for  word  splitting
          after  expansion  and  to  split  lines into words with the read
          builtin  command.   The  default  value  is  ``<space><tab><new-
          line>''.
ぶ宁プ宁ぶ 2024-12-29 07:27:49

这可能对你有用:

array=($(sed 'y/;/ /' <<<"1;2;3;4;5"))
for word in "${array[@]}"; do echo "$word"; done

This might work for you:

array=($(sed 'y/;/ /' <<<"1;2;3;4;5"))
for word in "${array[@]}"; do echo "$word"; done
寻梦旅人 2024-12-29 07:27:49
for w in $(echo '1;2;3;4;5' | tr \; \\n); do echo $w; done
for w in $(echo '1;2;3;4;5' | tr \; \\n); do echo $w; done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文