User
User

Reputation: 66081

How to add line number prefix to multi-line variable in shell scripting?

I want to display a numbered menu from a shell script (#!/bin/sh). Currently I use

echo "choice1
choice2
choice3
choice4
"

To output the menu. Now I want to add a number prefix to each line so the result will look like:

1) choice1
2) choice2
3) choice3
4) choice4
...

How can I do this without having to manually prefix each line with a number? I'm thinking I want to iterate over the variable line by line and concatenate the line number and output it to a new variable.

Upvotes: 2

Views: 727

Answers (2)

William Pursell
William Pursell

Reputation: 212634

select is probably the way to go, but you could also do:

echo "$string" | nl -ba -s') '

Upvotes: 2

Zsolt Botykai
Zsolt Botykai

Reputation: 51693

If you are using bash, I'd recommend using the select built-in for these kind of tasks.

Here are some examples.

Upvotes: 4

Related Questions