可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to get a specific line from a text file.
So far, online I have only seen stuff like sed, (I can only use the sh -not bash or sed or anything like that). I need to do this only using a basic shell script.
cat file | while read line
do
#do something
done
I know how to iterate through lines, as shown above, but what if I just need to get the contents of a particular line
回答1:
sed:
sed '5!d' file
awk:
awk 'NR==5' file
回答2:
Assuming line
is a variable which holds your required line number, if you can use head
and tail
, then it is quite simple:
head -n $line file | tail -1
If not, this should work:
x=0
want=5
cat lines | while read line; do
x=$(( x+1 ))
if [ $x -eq "$want" ]; then
echo $line
break
fi
done
回答3:
You could use sed -n 5p file
.
You can also get a range, e.g., sed -n 5,10p file
.
回答4:
I usually use this for this purpose:
sed '5q;d' file
回答5:
If for example you want to get the lines 10 to 20 of a file you can use each of these two methods:
head -n 20 york.txt | tail -11
or
sed -n '10,20p' york.txt
p
in above command stands for printing.
Here's what you'll see:
回答6:
The standard way to do this sort of thing is to use external tools. Disallowing the use of external tools while writing a shell script is absurd. However, if you really don't want to use external tools, you can print line 5 with:
i=0; while read line; do test $((++i)) = 5 && echo "$line"; done < input-file
Note that this will print logical line 5. That is, if input-file
contains line continuations, they will be counted as a single line. You can change this behavior by adding -r
to the read command. (Which is probably the desired behavior.)
回答7:
In parallel with William Pursell's answer, here is a simple construct which should work even in the original v7 Bourne shell (and thus also places where Bash is not available).
i=0
while read line; do
i=`expr "$i" + 1`
case $i in 5) echo "$line"; break;; esac
done <file
Notice also the optimization to break
out of the loop when we have obtained the line we were looking for.
回答8:
Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:
perl -e 'while(<>){if(++$l~~[1,3,5]){print}}' < /etc/passwd
回答9:
line=5; prep=`grep -ne ^ file.txt | grep -e ^$line:`; echo "${prep#$line:}"