【linux】打印字符串中指定行

只打印第10行 关键在于当行数小于10时不输出。

用 head tail的关键问题是当行数小于10的时候用 head -n 10 只会打出前面的行,再用tail就错了。

所以要知道源文件一共有多少行。用wc

wc -l  显示文件一共有多少行 -w列出有多少字(英文单字) -m列出有多少字符

但是得到了这个数字怎么用呢,需要一个变量存储行数,然后用if语句处理

加:

可以用 tail -n +10 表示从第10行开始显示,这样如果没有第10行就会显示空了

下面是多种答案:

num=$(cat file.txt|wc -l)
if (( $num > 9 )); then
 cat file.txt|head -10|tail -1
fi
STARTING=10; NLINES=1; cat file.txt | tail -n+${STARTING} | head -n${NLINES}
LINE_NUM=`head -n 10 file.txt | wc -l`

if (( $LINE_NUM == "10" )); then
 head -n 10 file.txt | tail -n 1 
else
 echo ""
fi
# Solution 1
cnt=0
while read line && [ $cnt -le 10 ]; do
  let 'cnt = cnt + 1'
  if [ $cnt -eq 10 ]; then
    echo $line
    exit 0
  fi
done < file.txt

# Solution 2
awk 'FNR == 10 {print }'  file.txt
# OR
awk 'NR == 10' file.txt

# Solution 3
sed -n 10p file.txt

# Solution 4
tail -n+10 file.txt|head -1

困惑:

①用if[  ]就出错??

②不用变量,直接写if (( `cat file.txt|wc -l` == 10 )) 也出错??

原文地址:https://www.cnblogs.com/dplearning/p/4551982.html