Reputation: 2140
I am trying to check if certain values (DIC, IC, RNDIC) are in a text file's first row but not in the first column. Sew below for all the detail. Not that each field in the text file is tabulated.
file.txt
NO DIC IC RNDIC FI BO CF
---
1 2 3 4 5 6
This is the code I have to deal with this file:
type=$(awk 'NR==1 {
for (i = 1; i <= NF; i++)
{
if (i != 1 && ($i == "DIC" || $i == "IC" || $i == "RNDIC"))
print "1"
}
}' $PWD/file.txt)
if [[ $type == "1" ]]; then
# rest of the code is irrelevant
fi
echo $type
The problem is that it never enters the if
statement after $type
is initialized. The reason is because $type
is actually 1 1
instead of 1
. I realize the mistake I made is with the if
statment in the for
loop but don't know how to fix it. Any suggestions? Thanks.
Let me know if further explanation is required.
Upvotes: 1
Views: 57
Reputation: 75458
No need to fork and rely on awk if you're using bash:
read -ra FIELDS < "$PWD/file.txt"
for A in "${FIELDS[@]:1}"; do
case "$A" in
DIC|IC|RNDIC)
# <do some things>
break
;;
esac
done
Or
function is_type1 {
local FIELDS A
read -ra FIELDS < "$1"
for A in "${FIELDS[@]:1}"; do
case "$A" in
DIC|IC|RNDIC)
return 0
;;
esac
done
return 1
}
if is_type1 "$PWD/file.txt"; then
# <do some things>
fi
Note: I just used case
since I don't know the version of bash and extglob
may be a hassle.
Upvotes: 1
Reputation: 784958
You can call exit
after printing 1
once:
type=$(awk 'NR==1 {
for (i = 1; i <= NF; i++) {
if (i != 1 && ($i == "DIC" || $i == "IC" || $i == "RNDIC")) {
print "1"
exit
}
}
}' $PWD/file.txt)
Upvotes: 1