Cyril F
Cyril F

Reputation: 1339

Loop through file to count field number

I have a script bash to add users from a .txt file. It is really simple:

name firstname uid gid

space separated values

I want to check with awk if each row contains 4 fields. If yes I want to return 1, if not return 0.

file=/my/file.txt
awk=$(awk -F' ' '{(NF != 4) ? res = 0 : res = 1; print res)}' $file)
echo $awk

Right now, awk returns 1 for each row, but I want it to return 1 or 0 at the end, not for each line in the file.

Upvotes: 2

Views: 267

Answers (3)

hek2mgl
hek2mgl

Reputation: 157967

On UNIX you'll return 0 in case of success and !=0 in case of an error. For me it makes more sense to return 0 when all records have 4 fields and 1 when not all records have 4 fields.

To achieve that, use exit:

awk 'NF!=4{exit 1}' file

FYI: awk will exit with 0 by default.

If you want to use it in a shell conditional:

#!/bin/bash
if ! awk 'NF!=4{exit 1}' file ; then
    echo "file is invalid"
fi

PS: -F' ' in your example is superfluous because ' ' is the default field delimiter.

Upvotes: 6

sjsam
sjsam

Reputation: 21965

Subtle changes to your script would do

result=$(awk -F' ' 'BEGIN{flag=1}NF!=4{flag=0;exit}END{print flag}' "$file")
[ ${result:-0} -eq 0 ] && echo "Problematic entries found in file"

The approach

  • set the flag to 1 hoping that every record would contain 4 fields.
  • check if record actually contains 4 fields, if not set flag to zero and exit.
  • And exit would skip the rest of the input and go to the END rule.
  • print the flag and store it in result.
  • Check the result and proceed with the action course.

Upvotes: 0

anubhava
anubhava

Reputation: 785098

You can use:

awk 'res = NF!=4{exit} END{exit !res}' file

This will exit with 1 if all rows have 4 columns otherwise it will exist with 0

Upvotes: 3

Related Questions