如何使用“头部”和“尾部”打印文件的特定行

时间:2013-04-01 17:06:56

标签: shell unix arguments tail unix-head

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

我如何使用headtail来执行此操作?

其中firstline = $2lastline = $3以及filename = $1

运行它应该如下所示:

./lines.sh filename firstline lastline

4 个答案:

答案 0 :(得分:26)

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 = $2lastline = $3filename = $1

head -n $lastline $filename | tail -n $(( $lastline -$firstline + 1 ))

答案 1 :(得分:17)

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

答案 2 :(得分:6)

试试这个单行:

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

在上面一行:

$begin is your $2
$end is your $3
$f is your $1

答案 3 :(得分:4)

将其另存为“ script.sh ”:

#!/bin/sh

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

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

NO ERROR HANDLING (为简单起见),所以你必须按照以下方式调用你的脚本:

./ script.sh yourfile.txt firstline lastline

$ ./script.sh yourfile.txt 5 10

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

$ ./script.sh yourfile.txt 10 10

请确保: (firstline&gt; 0)AND(lastline&gt; 0)AND(firstline&lt; = lastline)