Re: grabbing a piece of file

From: Chris F.A. Johnson (c.f.a.johnson_at_rogers.com)
Date: 09/25/03


Date: 25 Sep 2003 20:10:35 GMT

On Thu, 25 Sep 2003 at 07:06 GMT, Francesco wrote:
> Hi all,
> I'd like to write a program that collect a piece of a file. I should start
> with the first occurrence of an Id and finish with the last occurrence of
> it.
> Let me explain better: supposing the id is 999999
>
> ..............
> ..............
> 9999999 from here
> .............
> .............
> 9999999 to here
> ..............
>
> Can anybody give me a clue how to do it ?

    There are many ways; the best depends on several factors,
    including file size and whether the pattern you are searching for
    is on a line by itself or not.

    If the file is not too large to fit into memory:

[ $# -lt 2 ] && { echo "USAGE: ${0##*/} pattern file" >&2; exit; }
pattern=${1}
file=`cat "$2"` ## bash2: file=`< "$2"`
file="${file%"$pattern"*}$pattern"
file="$pattern${file#*"$pattern"}"
echo "$file"

    Otherwise there is Ed Morton's awk solution or this (which will
    probably be a bit slower than Ed's script):

[ $# -lt 2 ] && { echo "USAGE: ${0##*/} pattern file" >&2; exit; }
eval list=\"`grep -n "$1" "$2" | cut -d: -f1`\"
first=${list%% *}
last=${list##* }
sed -n "$first,$last p" "$2"

    ...though the while thing can probably be put into a sed script
    which would speed it up.

    If the pattern is not on a line by itself, then both my grep/sed
    script and Ed's awk script will return the entire line containing
    the first and last instances of the pattern.

-- 
    Chris F.A. Johnson                        http://cfaj.freeshell.org
    ===================================================================
    My code (if any) in this post is copyright 2003, Chris F.A. Johnson
    and may be copied under the terms of the GNU General Public License