我正在尝试编写一个shell脚本,询问用户要从文件中显示的行数,然后显示这些行。
我试图通过以下方式做到这一点:
#!/bin/bash
#author = johndoe
read -p "How many lines from /c/Users/johndoe/files/helpme.sh would you like to see? " USERLINEINPUT
LINE_NUM=1
while [ $LINE_NUM -lt $USERLINEINPUT ]
do
echo "$LINE_NUM: $USESRLINEINPUT"
((LINE_NUM++))
done < /c/Users/johndoe/files/helpme.sh
此代码似乎没有像我一样,请参阅下面的示例:
$ ./linecount.sh
How many lines from /c/Users/johndoe/files/helpme.sh would you line to see? 10
1:
2:
3:
4:
5:
6:
7:
8:
9:
答案 0 :(得分:1)
您的代码不符合您的要求。您需要将每行代码读入变量并打印出来。您的while循环仅满足用户输入值,并且您根本不打印文件行。请参阅下面的正确代码并看到您的错误。希望这会对你有所帮助: -
#!/bin/bash
#author = johndoe
LINE_NUM=1
read -p "How many lines from /c/Users/johndoe/files/helpme.sh would you like to see? " USERLINEINPUT
while read -r line
do
echo "$LINE_NUM:$line"
if [ $LINE_NUM -ge $USERLINEINPUT ]; then
break;
fi
((LINE_NUM++))
done < "/c/Users/johndoe/files/helpme.sh"
答案 1 :(得分:0)
#!/usr/bin/env bash
# file will be the first argument or helpme.sh by default
file=${1:-/c/Users/johndoe/files/helpme.sh}
# exit if the file is NOT readable
[[ -f $file && -r $file ]] || exit 1
# ask for a number and exit if the input is NOT a valid number
IFS= read -r -p "Number of lines from \"$file\": " num
[[ $num =~ ^[0-9]+$ ]] || exit 2
# 1st option: while/read
count=
while IFS= read -r line && ((count++<num)); do
printf '%d:%s\n' "$count" "$line"
done < "$file"
# 2nd option: awk
awk 'NR>ln{exit}{print NR":"$0}' ln="$num" "$file"