[olug] Grep Sed Question

Will Langford unfies at gmail.com
Sat Jun 16 02:46:08 UTC 2007


I couldn't think of a way to do it, but here's an entirely lame solution
using bash, grep, head, tail, and wc.  If you wanna have this as something
pipeable, then it's a bit more involved... and if it's just for a quick run
over a finite input should be possible... but not if it's supposed to be
running on something constantly generating output.

-Will

#!/bin/bash

# Simplified bashness to handle deleting a line of text, and the line
# preceding it from a file. Requires a command line parameter which
# should be the filename to read.  Output is stuffed into a file
# named {inputname}.new due to untrusted state of this script, even
# if it passes basic testing (first line, last line, not found conditions)

# To change the line to remove, you'll have to edit this script and
# change the HUNT= assignment ... or make HUNT=$2 ... just make sure
# to incase your second parameter in single or double quotes if it's
# more than one word. ie: script.sh input.txt 'new hunt string'

# This doesn't work as a piped script, and depending on it's uses,
# this might not be appropriate in bash.

# Currently only removes the first

HUNT="^text$" # regex happy to match whole line ?
LINES=0
LINESAFTER=0
INFILE=$1
OUTFILE=${INFILE}.new
LAST=0

if [ $# -lt 2 ] ; then
        echo "Usage: $0 [inputfile]"
fi

echo "INPUT: $INFILE"
echo "OUTPUT: $OUTFILE"
echo "HUNT: $HUNT"

grep "$HUNT" $INFILE &> /dev/null

if [ $? -eq 1 ] ; then
        echo "ERROR: '$HUNT' not found in $INFILE"
        exit 1
fi

LINE=`grep -n "$HUNT" $INFILE | head -n 1 | cut -d':' -f 1`
LINES=`cat $INFILE | wc -l`
LINESAFTER=$(($LINES - $LINE))

if [ $LINE -eq $LINES ] ; then
        LAST=1
fi

if [ $LINE -gt 1 ] ; then
        LINE=$(($LINE - 2))
        LINESAFTER=$(($LINESAFTER - 2))
else
        LINE=$(($LINE - 1))
fi

head -n $LINE $INFILE > $OUTFILE

if [ $LAST -eq 0 ] ; then
        tail -n $LINESAFTER $INFILE >> $OUTFILE
fi

echo "Done"


On 6/15/07, Stan Coleman <stan at srcproductions.com> wrote:
>
> I have a project where I want to remove a specific line from a text file.
> Piece of cake I've done that many times. Here is the twist I want to remove
> the specific line AND the line just prior to the specific line. Any
> thoughts?
> _______________________________________________
> OLUG mailing list
> OLUG at olug.org
> http://lists.olug.org/mailman/listinfo/olug
>



More information about the OLUG mailing list