我想说的输出线5 - 10的文件,作为参数传入。
我怎么会用head
和tail
做到这一点?
其中firstline = $2
和lastline = $3
和filename = $1
。
运行它应该是这样的:
./lines.sh filename firstline lastline
我想说的输出线5 - 10的文件,作为参数传入。
我怎么会用head
和tail
做到这一点?
其中firstline = $2
和lastline = $3
和filename = $1
。
运行它应该是这样的:
./lines.sh filename firstline lastline
除了给出的答案fedorqui和肯特 ,你也可以使用一个单一的sed
命令:
#! /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}
或者,为了避免任何外部UTILITES,如果你使用的是最新的bash(或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 -n XX # <-- print first XX lines
tail -n YY # <-- print last YY lines
如果你想从20线30,这意味着你需要11条线路从20日开始,在30后整理:
head -n 30 file | tail -n 11
#
# first 30 lines
# last 11 lines from those previous 30
也就是说,你首先得先30
线,然后选择最后11
(即30-20+1
)。
因此,在你的代码将是:
head -n $3 $1 | tail -n $(( $3-$2 + 1 ))
基于firstline = $2
, lastline = $3
, filename = $1
head -n $lastline $filename | tail -n $(( $lastline -$firstline + 1 ))
试试这个班轮:
awk -vs="$begin" -ve="$end" 'NR>=s&&NR<=e' "$f"
在上面的行:
$begin is your $2
$end is your $3
$f is your $1
Save this as "script.sh":
#!/bin/sh
filename="$1"
firstline=$2
lastline=$3
linestoprint=$(($lastline-$firstline+1))
tail -n +$firstline "$filename" | head -n $linestoprint
There is NO ERROR HANDLING (for simplicity) so you have to call your script as following:
./script.sh yourfile.txt firstline lastline
$ ./script.sh yourfile.txt 5 10
If you need only line "10" from yourfile.txt:
$ ./script.sh yourfile.txt 10 10
Please make sure that: (firstline > 0) AND (lastline > 0) AND (firstline <= lastline)