Loop through file to count field number

后端 未结 3 1859
一向
一向 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:29

    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.

提交回复
热议问题