Wednesday, December 2, 2009

Awk - Print first occurrence of a set


Input file 'order-pref.txt' contains two sql UPDATE commands for each item.

$ cat order-pref.txt
computer networking book
UPDATE orders SET quantity = '5' WHERE id = '9';
UPDATE orders SET quantity = '5' WHERE id = '8';
puzzle and skill games
UPDATE orders SET quantity = '5' WHERE id = '99';
UPDATE orders SET quantity = '5' WHERE id = '98';
arithmetic sequence
UPDATE orders SET quantity = '5' WHERE id = '55';
UPDATE orders SET quantity = '5' WHERE id = '56';

Required:
For each item find and print the first UPDATE sql command (i.e. first occurrence of each set of sql commands for each item).

i.e. required output:

UPDATE orders SET quantity = '5' WHERE id = '9';
UPDATE orders SET quantity = '5' WHERE id = '99';
UPDATE orders SET quantity = '5' WHERE id = '55';

Awk solution:

$ awk '/^UPDATE/{++c;if(c%2==1)print}' order-pref.txt > o.sql

Output:

$ cat o.sql
UPDATE orders SET quantity = '5' WHERE id = '9';
UPDATE orders SET quantity = '5' WHERE id = '99';
UPDATE orders SET quantity = '5' WHERE id = '55';

Related posts:

- Print first or last occurrence of pattern range using awk
- Print lines with more than two occurrence of a pattern using sed, awk, grep
- Count total occurrence of a pattern using awk
- Replace a field other than the first occurrence using awk
- Find pattern with maximum occurrence using awk
- Find nth occurrence of pattern in vi editor

2 comments:

Anbu said...

awk ' /^[^U]/{getline;print} ' order-pref.txt

Unknown said...

WS="[$(printf " \t\n")]"; # whitespace(space and TAB only) glob expression
set X;
while IFS= <&3 read -r Line; do
case $Line in
'UPDATE'$WS* )
case $# in [1357]) printf '%s\n' "$Line";; esac
set X ${1+"$@"};;
esac
done 3< order-pref.txt


sed -ne '
/^UPDATE\s/!d
G
/\n\(.\{2\}\)*$/P
s/.*\n/./; h

' order-pref.txt


perl -wMstrict -lne 'print if /^UPDATE\s/ && !($a++%2)' order-pref.txt

© Jadu Saikia www.UNIXCL.com