【问题标题】:Script that prints specific lines of a file打印文件特定行的脚本
【发布时间】:2020-04-30 11:06:05
【问题描述】:

我在使用此脚本时遇到了一些问题,该脚本将文件内容从给定行号打印到指定的下一个行号。如果 START 大于 END(例如 ./script file 10 7),我需要将 START 参数的行打印回 END 参数(基本上是第 10 行,然后是第 9 8 7 行)。

#!/bin/sh

START=$1
END=$2
FILENAME=$3

ERROR="[PINCH ERROR]"
if [ $# -lt 3 ]; then
    echo "$ERROR Need three arguments: Filename Start-line End-line"
    exit 1
fi

if [ ! -f "$FILENAME" ]; then
    echo -e "$ERROR File does not exist. \n\t$FILENAME"
    exit 1
fi

if [ "$START" -gt "$END" ]; then
    echo -e "$END $START"
    exit 1
fi

if [ "$START" -lt 0 ]; then
    echo -e "$ERROR Start line is less than 0."
    exit 1
fi

if [ "$END" -lt 0 ]; then
    echo -e "$ERROR End line is less than 0."
    exit 1
fi

NUMOFLINES=$(wc -l < "$FILENAME")

ENDDIFF=$(( NUMOFLINES - END ))

if [ "$START" -lt "$ENDDIFF" ]; then
    < "$FILENAME" head -n $END | tail -n +$START
else
    < "$FILENAME" tail -n +$START | head -n $(( END-START+1 ))
fi

exit 0 

【问题讨论】:

    标签: linux shell file


    【解决方案1】:

    既然你标记了这个 linux,你可能有 tac(1) 可用,这很容易:

    if [ "$START" -le "$END" ]; then
       # Normal output
       sed -n "${START},${END}p; ${END}q" "$FILENAME"
    else
        # Reverse output
        sed -n "${END},${START}p; ${START}q" "$FILENAME" | tac
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多