20

我想说输出文件的第 5-10 行,作为传入的参数。

我怎么能使用headtail做到这一点?

在哪里firstline = $2lastline = $3filename = $1

运行它应该是这样的:

./lines.sh filename firstline lastline
4

4 回答 4

37
head -n XX # <-- print first XX lines
tail -n YY # <-- print last YY lines

如果你想要从 20 到 30 的行,这意味着你想要从 20 开始到 30 结束的 11 行:

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 ))
于 2013-04-01T17:12:07.547 回答
16

除了fedorquiKent给出的答案之外,您还可以使用单个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}

或者,为了避免任何外部实用程序,如果您使用的是最新版本的 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
于 2013-04-01T17:37:48.943 回答
8

试试这个单行:

awk -vs="$begin" -ve="$end" 'NR>=s&&NR<=e' "$f"

在上面的行中:

$begin is your $2
$end is your $3
$f is your $1
于 2013-04-01T17:11:51.680 回答
4

将此另存为“ script.sh ”:

#!/bin/sh

filename="$1"
firstline=$2
lastline=$3
linestoprint=$(($lastline-$firstline+1))

tail -n +$firstline "$filename" | head -n $linestoprint

没有错误处理(为简单起见),因此您必须按以下方式调用脚本:

./script.sh yourfile.txt 第一行 最后一行

$ ./script.sh yourfile.txt 5 10

如果您只需要 yourfile.txt 中的“10”行:

$ ./script.sh yourfile.txt 10 10

请确保: (firstline > 0) AND (lastline > 0) AND (firstline <= lastline)

于 2014-01-25T19:02:17.807 回答