Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

shorter script using || 1

Status
Not open for further replies.

jdhahbi

Technical User
Oct 7, 2009
24
US
Hi
can you please suggest a more elegant, shorter script for printing lines where field #1 is equal to AA or BB or CC …. (sometimes more than 10 values).

awk '$1 == "AA" || $1 == "BB" || $1 == "CC"'

thank you
joseph
 
Hi

You could use a regular expression :
Code:
awk '[navy]$1[/navy][teal]~[/teal][fuchsia]/^(AA|BB|CC)$/[/fuchsia]' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].

But if using regular expression, then better use [tt]grep[/tt] :
Code:
grep -x 'AA\|BB\|CC' /input/file

[gray]# or[/gray]

grep -xE 'AA|BB|CC' /input/file
Especially GNU [tt]grep[/tt], but generally every [tt]grep[/tt] should be faster for this task.
joseph said:
(sometimes more than 10 values).
From where are those values coming ? If happens to have them in a file, one value per line, [tt]grep[/tt] is even more comfortable :
Code:
grep -Fxf /file/with/values /input/file
Tested with GNU [tt]grep[/tt].

Feherke.
 
Hi Feherke
thank you for your help.
can you specify filed #1 with grep?
joseph
 
Hi

Oops. I tested with my own test file with a single field and I forgot about the 1[sup]st[/sup] field requirement.

But for first and last field the workaround is simple : anchor its one side to the string's end and specify the delimiter on the other side :
Code:
grep '^\(AA\|BB\|CC\)\s' /input/file

[gray]# or[/gray]

grep -E '^(AA|BB|CC)\s' /input/file
For more exact reproduction of Awk's behavior you should allow spaces before the first field too :
Code:
grep '^\s*\(AA\|BB\|CC\)\s' /input/file

[gray]# or[/gray]

grep -E '^\s*(AA|BB|CC)\s' /input/file
But even so, the [tt]grep[/tt] solution is much faster than

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top