如何使用 Head 和 Tail 打印文件的特定行 [英] How do I use Head and Tail to print specific lines of a file
本文介绍了如何使用 Head 和 Tail 打印文件的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想说输出文件的第 5 - 10 行,作为传入的参数.
I want to say output lines 5 - 10 of a file, as arguments passed in.
我如何使用 head
和 tail
来做到这一点?
How could I use head
and tail
to do this?
其中 firstline = $2
和 lastline = $3
和 filename = $1
.
运行应该是这样的:
./lines.sh filename firstline lastline
推荐答案
除了 fedorqui 和 <一个 href="https://stackoverflow.com/a/15747983/1430833">Kent,你也可以使用单个 sed
命令:
Aside from the answers given by fedorqui and Kent, you can also use a single sed
command:
#!/bin/sh
filename=$1
firstline=$2
lastline=$3
# Basics of sed:
# 1. sed commands have a matching part and a command part.
# 2. The matching part matches lines, generally by number or regular expression.
# 3. The command part executes a command on that line, possibly changing its text.
#
# By default, sed will print everything in its buffer to standard output.
# The -n option turns this off, so it only prints what you tell it to.
#
# The -e option gives sed a command or set of commands (separated by semicolons).
# Below, we use two commands:
#
# ${firstline},${lastline}p
# This matches lines firstline to lastline, inclusive
# The command 'p' tells sed to print the line to standard output
#
# ${lastline}q
# This matches line ${lastline}. It tells sed to quit. This command
# is run after the print command, so sed quits after printing the last line.
#
sed -ne "${firstline},${lastline}p;${lastline}q" < ${filename}
或者,为了避免使用任何外部实用程序,如果您使用的是最新版本的 bash(或 zsh):
Or, to avoid any external utilites, if you're using a recent version of bash (or zsh):
#!/bin/sh
filename=$1
firstline=$2
lastline=$3
i=0
exec <${filename} # redirect file into our stdin
while read ; do # read each line into REPLY variable
i=$(( $i + 1 )) # maintain line count
if [ "$i" -ge "${firstline}" ] ; then
if [ "$i" -gt "${lastline}" ] ; then
break
else
echo "${REPLY}"
fi
fi
done
这篇关于如何使用 Head 和 Tail 打印文件的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文