如何为输出添加行号,提示换行,然后根据输入进行操作?

时间:2012-02-25 11:46:58

标签: linux shell

我写了一个像这样的shell脚本:

#! /bin/sh
...
ls | grep "android"
...

,输出为:

android1 
android2
xx_android
...

我想在每个文件中添加一个数字,如下所示:

    1 android1 
    2 android2
    3 XX_android
    ...
    please choose your dir number:

然后等待用户输入行号x,脚本读回行号然后处理相应的目录。我们怎么能在shell中做到这一点?谢谢!

6 个答案:

答案 0 :(得分:194)

nl打印行号:

ls | grep android | nl

答案 1 :(得分:40)

如果您将结果导入cat,则可以使用-n选项为每行编号,如下所示:

ls | grep "android" | cat -n

答案 2 :(得分:14)

-n传递给grep,如下所示:

ls | grep -n "android"

来自grep手册页:

 -n, --line-number
        Prefix each line of output with the line number within its input file.

答案 3 :(得分:11)

您可以使用内置命令select

,而不是实现交互
select d in $(find . -type d -name '*android*'); do
    if [ -n "$d" ]; then
        # put your command here
        echo "$d selected"
    fi
done

答案 4 :(得分:0)

这对我有用:

line-number=$(ls | grep -n "android" | cut -d: -f 1)

我在脚本中使用它来删除我的sitemap.xml部分,我不想让Googlebot抓取。我搜索URL(这是唯一的),然后使用上面的代码找到行号。使用简单的数学,脚本然后计算删除XML文件中的整个条目所需的数字范围。

我同意jweyrich关于更新你的问题以获得更好的答案。

答案 5 :(得分:0)

此页面上的其他答案实际上并未100%回答问题。它们没有显示如何让用户以交互方式从另一个脚本中选择文件。

以下方法将允许您执行此操作,如示例中所示。请注意,select_from_list脚本已被提取from this stackoverflow post

$ ls 
android1        android4        android7        mac2            mac5
android2        android5        demo.sh         mac3            mac6
android3        android6        mac1            mac4            mac7

$ ./demo.sh
1) android1  3) android3  5) android5  7) android7
2) android2  4) android4  6) android6  8) Quit
Please select an item: 3
Contents of file selected by user: 2.3 Android 1.5 Cupcake (API 3)

以下是demo.sh以及用于从列表中选择项目的脚本select_from_list.sh

demo.sh

#!/usr/bin/env bash

# Ask the user to pick a file, and 
# cat the file contents if they select a file.
OUTPUT=$(\ls | grep android | select_from_list.sh | xargs cat)
STATUS=$? 

# Check if user selected something
if [ $STATUS == 0 ]
then
  echo "Contents of file selected by user: $OUTPUT"
else
  echo "Cancelled!"
fi

select_from_list.sh

#!/usr/bin/env bash

prompt="Please select an item:"

options=()

if [ -z "$1" ]
then
  # Get options from PIPE
  input=$(cat /dev/stdin)
  while read -r line; do
    options+=("$line")
  done <<< "$input"
else
  # Get options from command line
  for var in "$@" 
  do
    options+=("$var") 
  done
fi

# Close stdin
0<&-
# open /dev/tty as stdin
exec 0</dev/tty

PS3="$prompt "
select opt in "${options[@]}" "Quit" ; do 
    if (( REPLY == 1 + ${#options[@]} )) ; then
        exit 1

    elif (( REPLY > 0 && REPLY <= ${#options[@]} )) ; then
        break

    else
        echo "Invalid option. Try another one."
    fi
done    
echo $opt