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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

awk: print lines only when two lines with $NF == "string" found. 1

Status
Not open for further replies.

w5000

Technical User
Nov 24, 2010
223
PL

hello,

print no line if only one or more than two has been found.

$ echo "1 2 3 stringA\n3 4 5 stringA"|awk '$NF == "stringA"'
1 2 3 stringA
3 4 5 stringA

current workaround:
TEST_INPUT="1 2 3 stringA\n3 4 5 stringB"
if [ `echo ${TEST_INPUT}|awk '$NF == "stringA"'|wc -l` -eq 2 ]
then
echo ${TEST_INPUT}|awk '$NF == "stringA"'
fi

can it be done with the only 'awk' command in:

echo "1 2 3 stringA\n3 4 5 stringB"|[red]awk '$NF == "stringA"'[/red]

 
Hi

This is a typical case for double passing : first just count, when just output :
Code:
awk '[navy]FNR[/navy][teal]==[/teal]NR[teal]{[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green][teal]&&[/teal]c[teal]++;[/teal][b]next[/b][teal]}[/teal][navy]c[/navy][teal]==[/teal][purple]2[/purple][teal]&&[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green]' /input/file /input/file

In case your input will come from the standard input, will need the shell's process substitution feature :
Code:
awk '[navy]FNR[/navy][teal]==[/teal]NR[teal]{[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green][teal]&&[/teal]c[teal]++;[/teal][b]next[/b][teal]}[/teal][navy]c[/navy][teal]==[/teal][purple]2[/purple][teal]&&[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green]' <( echo "$TEST_INPUT" ) <( echo "$TEST_INPUT" )

In case the input is huge, is preferable to use optimized code, even if it is abit longer :
Code:
awk '[navy]FNR[/navy][teal]==[/teal]NR[teal]{[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green][teal]&&[/teal]c[teal]++;[/teal][b]next[/b][teal]}[/teal][navy]FNR[/navy][teal]==[/teal][purple]1[/purple][teal]&&[/teal]c[teal]!=[/teal][purple]2[/purple][teal]{[/teal][b]exit[/b][teal]}[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green]' /input/file /input/file

[gray]# or[/gray]

awk '[navy]FNR[/navy][teal]==[/teal]NR[teal]{[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green][teal]&&[/teal]c[teal]++;[/teal][b]next[/b][teal]}[/teal][navy]FNR[/navy][teal]==[/teal][purple]1[/purple][teal]&&[/teal]c[teal]!=[/teal][purple]2[/purple][teal]{[/teal][b]exit[/b][teal]}[/teal][navy]$NF[/navy][teal]==[/teal][green][i]"stringA"[/i][/green]' <( echo "$TEST_INPUT" ) <( echo "$TEST_INPUT" )

Feherke.
[link feherke.github.com/][/url]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top