Number of columns

Hi All

I am using the below code to check the number of columns in a delimited file are same as expected. Code is give below

awk -F '|' -v line=$2 'NF!=line {print NF,$0}' file

Here the challenge is that , delimiter is different for each file, it can be pipe, comma, or semi colon.I want to pass the delimiter value into the above awk command using external parameter.Currently I am passing the number of fields as external parameter.

Kindly help me on this

Hello ginrkf,

Here is an example for this you could set it as follows.

VAL="|"
awk '{print $1}' FS="$VAL" Input_file

Similarly you could set it for any file as per your need. As you haven't shown us complete requirement so one could take it as a starting point, let me know if this helps.

Thanks,
R. Singh

Actually my requirement is to find out where the number of columns present in the file is same a predefined.

I have two files A & B

A is suppose to have three columns and is a pipe delimited file

1|2|3
3|4
5|6|7

I want to write a awk command to find the records where number of columns are not equal to three.So if run my awk command to the file A, I should get out put as

3|4

B is suppose to have two columns and is a comma delimiter file

1,2
3,4
5

I want to write a awk command to find the records where number of columns are not equal to two.So if run my awk command to the file B, I should get out put as

5

What I need is a command command where I will be able to pass the number of columns and delimiter as external parameter while running the script.If you see my below script I am passing number of columns as a parameter

awk -F '|' -v line=$2 'NF!=line {print NF,$0}' file

In addition to that I need to pass the delimiter also as a parameter. I tried like below, but not working

VAL=$1 awk -v line=$2 'NF!=line {print NF,$0}' FS=$VAL file

You also want to pass the filename.?

awk -F "$3" -v line="$2" 'NF!=line {print NF,$0}' "$1"

Put this in a script or in a function.
And run it like this

myfunc "file" 3 "|"
1 Like

If you invoke your script with two parameters where the 1st parameter is the field separator and the 2nd parameter is the expected number of fields, just using:

awk -F "$1" -v cnt="$2" 'NF!=cnt {print NR,NF,$0}' file

will give you output where each line is the line number of a line with the wrong number of fields, the number of fields found on that line, and the text from that line. Another way to write that awk script and get identical results would be:

awk 'NF!=cnt {print NR,NF,$0}' FS="$1" cnt="$2" file
2 Likes