当前位置: 动力学知识库 > 问答 > 编程问答 >

unix - 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.

网友答案:

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

Here are some examples.

网友答案:

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

echo "$string" | nl -ba -s') '
分享给朋友:
您可能感兴趣的文章:
随机阅读: