Print Unknown Number of User Inputs in awk

Hello,

I am new to awk and I am trying to figure out how to print an output based on user input.

For example:


ubuntu:~/scripts$ steps="step1, step2, step3"

ubuntu:~/scripts$ echo $steps
step1, step2, step3

I am playing around and I got this pattern that I want:


ubuntu:~/scripts$ echo $steps | awk -F, '{print "Step Taken:" "\n" "- "$1 "\n" "-"$2 "\n" "-" $3}'

Step Taken:
- step1
- step2
- step3

The question is this:

What if the users input 4 or more steps (always separated by comma which I will use as a field separator just like the example above)?

How can I print an output that will include step4 or more like this?

Step Taken:
- step1
- step2
- step3
- step4
- step5

So on and so forth...

Thanks!

Hello tattoostreet,

You could try following for same.

steps="step1, step2, step3, step4, step5, step7, step8, step9, step10"
echo $steps  | awk -F", " '{for(i=1;i<=NF;i++){print $i}}'

Output will be as follows.

step1
step2
step3
step4
step5
step7
step8
step9
step10
 

Thanks,
R. Singh

1 Like

This is what I need!! Thank you so much!

Try also

steps=" step1, step2, step3, step4, step5, step7, step8, step9, step10"
echo "$steps" | tr ' ,' '-\n'
-step1
-step2
-step3
-step4
-step5
-step7
-step8
-step9
-step10

( this needs a leading space before step1)

---------- Post updated at 19:54 ---------- Previous update was at 19:51 ----------

or

echo "${steps//, /    
- }"
 step1
- step2
- step3
- step4
- step5
- step7
- step8
- step9
- step10

(Here, even a leading space doesn't help)

1 Like