Loop through file to count field number

后端 未结 3 1860
一向
一向 2021-01-21 23:48

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

3条回答
  •  无人及你
    2021-01-22 00:37

    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.

提交回复
热议问题