Oprócz odpowiedzi udzielonych przez fedorqui i Kent, można również użyć jednego sed
polecenie:
#! /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}
Lub, aby uniknąć jakichkolwiek zewnętrznych narzędziowych, jeśli używasz najnowszej wersji bash (lub 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
@ user2232423 Wszystkie polecenia Unix mają standardowe wejście (stdin) i standardowe wyjście (stdout). Polecenia 'sed',' awk' i wiele innych (w tym 'head' i' tail') odczytują ich wejście ze stdin, przetwarzają je i zapisują wyniki na standardowe wyjście. Domyślnie stdin/stdout są dołączone do terminala. Używając przekierowania (np .: 'COMMAND < FILE1 > FILE2'), możesz ustawić stdin dla' COMMAND', aby odczytać z 'FILE1' i stdout, aby zapisać do' FILE2'. Jest to fundamentalne dla Uniksa; możesz zapoznać się z samouczkiem (http://www.ceri.memphis.edu/computer/docs/unix/bshell.htm) lub książką, aby uzyskać lepsze zrozumienie. – sfstewman
@ user2232423 Ponadto zarówno 'awk', jak i' sed' oferują dużą moc do przetwarzania tekstu. Jeśli zamierzasz spędzać dużo czasu w Uniksie, te dwa polecenia (plus 'grep') będą bardzo, bardzo użyteczne. Warto się uczyć, choć łatwiej się ich nauczyć w małych kawałkach na raz. Możesz znaleźć [sed & awk] (http://shop.oreilly.com/product/9781565922259.do) jako przydatną książkę. – sfstewman
Dzięki, świetna rada. Mam kilka rzeczy, których nie jestem pewien, np. W jaki sposób sed dopasowuje linie z kodem tak prostym, jak $ {firstline}, $ {lastline} p <<, co właściwie tam się dzieje? –