如何從Unix上的文本文件中提取預約範圍的行?

我有一個~23000行的SQL轉儲包含幾個數據庫的數據。 我須要提取此文件的某個部分(即單個數據庫的數據)並將其放在一個新文件中。 我知道我想要的數據的起始行和結束行號。 數據庫

有沒有人知道一個Unix命令(或一系列命令)從第16224和16482行之間的文件中提取全部行,而後將它們重定向到一個新文件? bash


#1樓

我會用: less

awk 'FNR >= 16224 && FNR <= 16482' my_file > extracted.txt

FNR包含從文件中讀取的行的記錄(行)編號。 ui


#2樓

我編寫了一個名爲splitter的Haskell程序,它正是這樣作的: 閱讀個人發佈博客文章this

您能夠按以下方式使用該程序: spa

$ cat somefile | splitter 16224-16482

這就是它的所有內容。 您將須要Haskell來安裝它。 只是: 命令行

$ cabal install splitter

你完成了。 我但願你發現這個程序頗有用。 code


#3樓

awk還有另外一種方法: three

awk 'NR==16224, NR==16482' file

若是文件很大,最好在讀取最後一行後exit 。 這樣,它就不會沒必要要地讀取如下行: terminal

awk 'NR==16224, NR==16482-1; NR==16482 {print; exit}' file

#4樓

即便咱們能夠在命令行檢查:

cat filename|sed 'n1,n2!d' > abc.txt

例如:

cat foo.pl|sed '100,200!d' > abc.txt

#5樓

我寫了一個小的bash腳本,您能夠從命令行運行,只要您更新PATH以包含其目錄(或者您能夠將它放在已包含在PATH中的目錄中)。

用法:$ pinch filename起始行結束行

#!/bin/bash
# Display line number ranges of a file to the terminal.
# Usage: $ pinch filename start-line end-line
# By Evan J. Coon

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

ERROR="[PINCH ERROR]"

# Check that the number of arguments is 3
if [ $# -lt 3 ]; then
    echo "$ERROR Need three arguments: Filename Start-line End-line"
    exit 1
fi

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

# Check that start-line is not greater than end-line
if [ "$START" -gt "$END" ]; then
    echo -e "$ERROR Start line is greater than End line."
    exit 1
fi

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

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

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

# Check that end-line is not greater than the number of lines in the file.
if [ "$END" -gt "$NUMOFLINES" ]; then
    echo -e "$ERROR End line is greater than number of lines in file."
    exit 1
fi

# The distance from the end of the file to end-line
ENDDIFF=$(( NUMOFLINES - END ))

# For larger files, this will run more quickly. If the distance from the
# end of the file to the end-line is less than the distance from the
# start of the file to the start-line, then start pinching from the
# bottom as opposed to the top.
if [ "$START" -lt "$ENDDIFF" ]; then
    < "$FILENAME" head -n $END | tail -n +$START
else
    < "$FILENAME" tail -n +$START | head -n $(( END-START+1 ))
fi

# Success
exit 0
相關文章
相關標籤/搜索