Jakub
Jakub

Reputation: 699

Print only once if something specific name is in the file

I have a problem. This is my script:

#!/bin/bash
file_name="eq3_luteina_horyzontalna"
file_name2="wiazanie_PO4"
tmp=$(mktemp) || exit 1  
for index in {1..405000} 
do
if ! [ -s "${file_name}_$index.ndx" ];then
    echo "0" >> ${file_name2}_POP42.txt
else
    awk '{if($2==/POP42/) print "5"; else print "0"}' ${file_name}_$index.ndx >> ${file_name2}_POP42.txt
fi
done

The problem is here

awk '{if($2==/POP42/) print "5"; else print "0"}' ${file_name}_$index.ndx

I want to only check if POP42 is in the file in the second column and print 5 but I have data like that

162 POP87
1851 POP42

so it will print into my output file ${file_name2}_POP42.txt, something like that:

0
5

but I want to have

5

Another situation

3075 POP42
2911 POP42

It will print to output

5
5

but I want only

5

How can I manage my problem?

Upvotes: 0

Views: 86

Answers (1)

Ed Morton
Ed Morton

Reputation: 203209

awk '$2=="POP42"{s=5; exit} END{print s+0}' file

By the way - $2==/POP42/ doesn't do what you think it does, i.e. look for lines with $2 equal to (or even containing) POP42. It's actually shorthand for $2==($0 ~ /POP42/ ? 1 : 0) courtesy of the regexp delimiters /.../ you used and what THAT does is see if a string matching the regexp POP42 occurs anywhere on the current line and, if it does, then test to see if $2 has the value 1, otherwise test to see if $2 has the value 0. It's important to know the difference between string (") and regexp (/) delimiters and string (e.g. ==) and regexp (e.g. ~) comparison operators when using awk.

Upvotes: 5

Related Questions