简体   繁体   English

while 循环回显变量,直到 Bash 中为空

[英]while loop to echo variable until empty in Bash

Here is what we have in the $foo variable:这是我们在$foo变量中的内容:

abc bcd cde def

We need to echo the first part of the variable ONLY, and do this repeatedly until there's nothing left.我们只需要回显变量的第一部分,并重复执行此操作,直到没有任何剩余。

Example:例子:

$ magic_while_code_here
I am on abc
I am on bcd
I am on cde
I am on def

It would use the beginning word first, then remove it from the variable.它将首先使用开头的单词,然后将其从变量中删除。 Use the beginning word first, etc. until empty, then it quits.先用开头的词,以此类推,直到空,然后退出。

So the variable would be abc bcd cde def , then bcd cde def , then cde def , etc.所以变量将是abc bcd cde def ,然后是bcd cde def ,然后是cde def ,等等。

We would show what we have tried but we are not sure where to start.我们会展示我们已经尝试过的东西,但我们不确定从哪里开始。

Assuming the variable consist of sequences of only alphabetic characters separated by space or tabs or newlines, we can (ab-)use the word splitting expansion and just do printf :假设变量仅包含由空格或制表符或换行符分隔的字母字符序列,我们可以(ab-)使用分词扩展,只需执行printf

foo="abc bcd cde def"
printf "I am on %s\n" $foo

will output:将 output:

I am on abc
I am on bcd
I am on cde
I am on def

If you need to use the while loop and cut the parts from the beginning of the string, you can use the cut command.如果需要使用 while 循环并从字符串的开头剪切部分,可以使用cut命令。

foo="abc bcd cde def"

while :
do
  p1=`cut -f1 -d" " <<<"$foo"`
  echo "I am on $p1"
  foo=`cut -f2- -d" " <<<"$foo"`
  if [ "$p1" == "$foo" ]; then
    break
  fi
done

This will output:这将 output:

I am on abc
I am on bcd
I am on cde
I am on def

I would use read -a to read the string into an array, then print it:我会使用read -a将字符串读入一个数组,然后打印它:

$ foo='abc bcd cde def'
$ read -ra arr <<< "$foo"
$ printf 'I am on %s\n' "${arr[@]}"
I am on abc
I am on bcd
I am on cde
I am on def

The -r option makes sure backslashes in $foo aren't interpreted; -r选项确保不解释$foo中的反斜杠; read -a allows you to have any characters you want in $foo and split on whitespace. read -a允许您在$foo中包含任何您想要的字符并在空格上拆分。


Alternatively, if you can use awk, you could loop over all fields like this:或者,如果您可以使用 awk,您可以像这样遍历所有字段:

awk '{for (i=1; i<=NF; ++i) {print "I am on", $i}}' <<< "$foo"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM