2

Here is what we have in the $foo variable:

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.

We would show what we have tried but we are not sure where to start.

3 Answers 3

3

If you need to use the while loop and cut the parts from the beginning of the string, you can use the cut command.

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:

I am on abc
I am on bcd
I am on cde
I am on def
Sign up to request clarification or add additional context in comments.

1 Comment

Note that backticks ` are discouraged. The $( .. ) command substitution is greatly preferred.
2

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:

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

will output:

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

Comments

2

I would use read -a to read the string into an array, then print it:

$ 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; read -a allows you to have any characters you want in $foo and split on whitespace.


Alternatively, if you can use awk, you could loop over all fields like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.