题目:
How would you print just the 10th line of a file?
For example, assume that file.txt
has the following content:
Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10Your script should output the tenth line, which is:
Line 10
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# Read from the file words.txt
and
output the word frequency list to stdout.
#!/bin/bash
#其中反引号的作用就是将反引号内的Linux命令先执行,然后将执行结果赋予变量。
#先用wc -l命令找到file.txt文件共有多少行,其中有两个字段第一个是行数,第二个是文件名。
#通过awk命令找出第一个字段
$1
,将行数赋给rownum
rownum=`wc -l file.txt | awk
'{print $1}'
`
#如果行数小于10,则返回空字符串
if
[
$rownum
-lt 10 ]; then
echo
""
#如果行数大于等于10,则通过sed命令先删除前9行,然后通过head命令打印出剩下的第一行
else
sed
'1,9d'
file.txt | head -1
fi
|
注意:
sed
'1,9d'
file.txt | head -1
这一行代码中的'1,9d'是指删除1到9行,输出剩余内容。但是不会真的删除file.txt中的内容。
不过在网上发现几个非常好的方法,算是学习了
1、用awk方法
1
|
awk
'NR == 10'
file.txt
|
1
|
sed -n
'10p'
file.txt
|
1
|
tail -n +10 file.txt | head -n 1
|