1756273 Members
2491 Online
108843 Solutions
New Discussion юеВ

Script help...awk

 
SOLVED
Go to solution
Coolmar
Esteemed Contributor

Script help...awk

How can I grep on a line in a file and then print/get the line above it?

Thanks

IE:

linea
lineb
linec
lined

grep linec | awk print linec and lineb
4 REPLIES 4
KapilRaj
Honored Contributor
Solution

Re: Script help...awk

cat file | while read line
do
grep "string" $line 1>/dev/null 2>/dev/null
if [ $? -eq 0 ]
then
echo ${lastline}
echo ${line}
fi
lastline=${line}
done

I know there is a bug if the string comes on the first line. I can not think of a solution for it. May be the perl masters will give you a good colution.

Regards,

Kaps
Nothing is impossible
Peter Godron
Honored Contributor

Re: Script help...awk

Hi,
#!/usr/bin/sh
end=`grep -n linec file | awk -F':' '{print $1}'`
start=`expr $end - 1`
sed -n '$start,$endp' file


or better:
get gnu grep and do:
grep -B1 linec
spex
Honored Contributor

Re: Script help...awk

Hi Coolmar,

# cat file
linea
lineb
linec
lined

# awk '/linec/{print x; print};{x=$0}' file
lineb
linec

PCS
Coolmar
Esteemed Contributor

Re: Script help...awk

Thanks folks!