如何使用头尾打印文件的特定行 [英] How do I use Head and Tail to print specific lines of a file
本文介绍了如何使用头尾打印文件的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想说的输出线路5 - 10的文件,作为参数传递
。我怎么能使用头
和尾
来做到这一点?
其中, FIRSTLINE = $ 2
和 lastLine所= $ 3
和文件名= $ 1
。
运行它应该是这样的:
./ lines.sh名FIRSTLINE lastLine所
解决方案
除了通过 fedorqui 和<给出的答案A HREF =http://stackoverflow.com/a/15747983/1430833>肯特,你也可以使用一个单一的 SED
命令:
#! / bin / sh的
文件名= $ 1
FIRSTLINE = $ 16
lastLine所= $ 3sed的基础#:
#1,sed命令有一个匹配的部分和命令部分。
#2,匹配的部分匹配线,一般由数字或定期EX pression。
#3,命令一部分在该行执行的命令,可能改变其文本。
#
#默认情况下,sed的将打印在它的缓冲区到标准输出的一切。
#-n选项开启这个功能,所以只打印你告诉它。
#
#-e选项给出的sed命令或一组命令(用分号分隔)。
#下面,我们用两个命令:
#
#$ {FIRSTLINE} $ {lastLine所} p
#这与FIRSTLINE到lastLine所,包容线
#命令'P'告诉sed打印行到标准输出
#
#$ {} lastLine所q
#这与线$ {} lastLine所。它告诉sed将退出。此命令
#在印刷好最后行之后打印命令后运行,所以SED退出。
#
SED -ne$ {FIRSTLINE} $ {} lastLine所磷; $ {} lastLine所Q&LT; $ {文件名}
或者,要避免任何外部的公用设施,如果您使用的是bash的近期(或zsh中)的版本:
#! / bin / sh的文件名= $ 1
FIRSTLINE = $ 16
lastLine所= $ 3I = 0
EXEC&LT; $ {文件名}#重定向文件到我们的标准输入
而阅读;做阅读#每行到变量REPLY
我= $(($ I + 1))#保持行数 如果[$ I-ge$ {FIRSTLINE}];然后
如果[$ I-gt$ {} lastLine所];然后
打破
其他
回声$ {} REPLY
科幻
科幻
DONE
I want to say output lines 5 - 10 of a file, as arguments passed in.
How could I use head
and tail
to do this?
where firstline = $2
and lastline = $3
and filename = $1
.
Running it should look like this:
./lines.sh filename firstline lastline
解决方案
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}
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
这篇关于如何使用头尾打印文件的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文