如何在不使用外部命令的情况下通过Unix Shell中的字符串字符迭代?

发布于 2025-01-27 13:45:16 字数 118 浏览 4 评论 0原文

这不是bash。这是sh。 $ {foo:0:1}不起作用。导致不良替代。

foo =“ Hello”

如何单独打印每个字符?我正在寻找一种不需要外部命令的方法。

This is not bash. This is sh. ${foo:0:1} doesn't work. Results in bad substitution.

foo="Hello"

How do i print each character individually? I am looking for an approach that requires no external commands.

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

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

发布评论

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

评论(3

辞取 2025-02-03 13:45:16

扩展我的评论:传统的伯恩·贝壳(Bourne Shell)确实没有更现代的外壳可用的弦乐操作的内置设施。您将依靠外部程序来获得这些功能,这是

例如,使用剪切之类的简单内容,我们可以写:

foo="hello"

len=$(echo "$foo" | wc -c)
i=1

while [ "$i" -lt "${len}" ]; do
  echo "$foo" | cut -c"$i"
  i=$(( i + 1 ))
done

哪个将输出:

h
e
l
l
o

cut之类的命令是“标准” shell scripting命令,尽管没有内置在shell中本身。

Expanding on my comment: the traditional Bourne shell doesn't really have the sort of built-in facilities for string manipulation that are available in more modern shells. It was expected that you would rely on external program for these features.

For example, using something as simple as cut, we could write:

foo="hello"

len=$(echo "$foo" | wc -c)
i=1

while [ "$i" -lt "${len}" ]; do
  echo "$foo" | cut -c"$i"
  i=$(( i + 1 ))
done

Which would output:

h
e
l
l
o

Commands like cut are "standard" shell scripting commands, despite not being built into the shell itself.

才能让你更想念 2025-02-03 13:45:16

larsks 答案您必须依靠外部命令。

我建议使用单个awk调用,而不是一次运行外部程序以获取字符串长度,而是对每个索引反复重复。

foo="hello world"

awk -v "s=$foo" 'BEGIN { l=length(s); for(i=1; i<=l; i++) print substr(s,i,1)}' /dev/null

当然

h
e
l
l
o

w
o
r
l
d

,您可以将进一步的处理添加到awk脚本或读取和处理输出之类的输出,例如

awk ... | while IFS= read -r char
...

请参见 https://mywiki.wooledge.org/bashfaq/001

As written in larsks's answer you have to rely on external commands.

Instead of running external programs once to get the string length and repeatedly for every index, I suggest to use a single awk call.

foo="hello world"

awk -v "s=$foo" 'BEGIN { l=length(s); for(i=1; i<=l; i++) print substr(s,i,1)}' /dev/null

which prints

h
e
l
l
o

w
o
r
l
d

Of course you could add further processing to the awk script or read and process the output like

awk ... | while IFS= read -r char
...

see https://mywiki.wooledge.org/BashFAQ/001

寒江雪… 2025-02-03 13:45:16

建议awk

awk '{for(i=1;i<=NF;i++)print $i}' FS="" <<<$(echo "$foo")

建议bash

#!/bin/bash
foo="hello me"
for ((i = 0 ; i < ${#foo}; i++)); do
  echo "${foo:$i:1}"
done

suggesting awk:

awk '{for(i=1;i<=NF;i++)print $i}' FS="" <<<$(echo "$foo")

suggesting bash:

#!/bin/bash
foo="hello me"
for ((i = 0 ; i < ${#foo}; i++)); do
  echo "${foo:$i:1}"
done
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文