Print the first word based on the last 5 words from the file
I have a file with the content below and I want to print the first word only if it starts with P
and if the last 5 characters12
File:
papa;1;2;3;4;5;12;12;12;12;12 Peter;12;12;12;12;12 alpha;2;2;2;4;5;6;7;8;9;3;3;3;3;3 Prod;1;2;3;4;1;1;1;1;12;12;12;12;12
Expected Result:
Peter
Prod
My attempt:
cat filename | awk -F '[;]' '{print substr( $0,length($0)-5,length($0))}'
cat filename | egrep -V 'p|a' | awk -F '[;]' '{print $1}'
But I couldn't join the exit.
Update: -
From the comments in the accepted answer, obviously the OP is saying that there may also be lines of less than 5 fields in the final file.
source to share
Rough way to do it in Awk
just for the first word
awk -F';' '$1 ~ /^P/ && NF > 5 {c=0; for(i=NF-4;i<=NF;i++) {if($i==12){c++}} if(c==5) print $1} ' file
Peter
Prod
and if the whole line is needed, remove $1
in print
statement
awk -F';' '$1 ~ /^P/ && NF > 5 {c=0; for(i=NF-4;i<=NF;i++) {if($i==12){c++}} if(c==5) print} ' file
Peter;12;12;12;12;12
Prod;1;2;3;4;1;1;1;1;12;12;12;12;12
How it works?
- The part
$1 ~ "^P"
is a regular match for filtering lines starting withP
- On the lines starting with above, parse the last 5 fields (loop with
NF
and maintaining a counter and print the line if 5 instances are found12
.
source to share
Here's another one with awk
$ cat ip.txt
papa;1;2;3;4;5;12;12;12;12;12
Peter;12;12;12;12;12
alpha;2;2;2;4;5;6;7;8;9;3;3;3;3;3
Prod;1;2;3;4;1;1;1;1;12;12;12;12;12
Post;1;3;12;12;12
$ awk -F';' '/^P.*(;12){5}$/{print $1}' ip.txt
Peter
Prod
-
/^P.*(;12){5}$/
a line starting withP
ends with;12;12;12;12;12
source to share
another approach of recursive checks, with everything in variables. Let me know if this helps you.
awk -F";" -v num=12 -v count=5 -v cha="P" 'function check(count){if($(NF-(--count))==num && count){check(count)};if(!count && substr($0,1,1)==cha){print $1}} check(count)' Input_file
Will soon add more than one liner form and explanation of the above code.
EDIT1: Adding more than one linear form of the solution too.
awk -F";" -v num=12 -v count=5 -v cha="P" '
function check(count){
if($(NF-(--count))==num && count){
check(count)
};
if(!count && substr($0,1,1)==cha){
print $1
}
}
check(count)
' Input_file
source to share