Unix - Count of Columns in File

unix - count of columns in file


awk -F'|' '{print NF; exit}' stores.dat 

Just quit right after the first line.

How do I count the number of rows and columns in a file using bash?

Columns: awk '{print NF}' file | sort -nu | tail -n 1

Use head -n 1 for lowest column count, tail -n 1 for highest column count.

Rows: cat file | wc -l or wc -l < file for the UUOC crowd.

Count the number of rows per column in Bash Shell

Based on assumption of required output, you have given

$ cat testfile 
ID Name
------------
13 Sara
22 Suzan
null Mark
49 John

$ awk '$1 ~ /^[0-9]*$/{ count++ }END{print count}' testfile
3

$ awk 'function is_num(x){return(x==x+0);} is_num($1){ count++ }END{print count}' testfile
3

awk to find number of columns for each line and exit if more than required

Sure you can do:

awk -F, 'NF > 1{exit} 1' file

This will give output as:

ME
TEST
HELLO
WORLD

as NF>1 condition exits the awk as soon as there are more than 1 columns.


EDIT: As per comments below OP wants to print first row with 2 columns and exit. This command should work:

awk -F, 'NF > 1{print; exit}' file
BOO,HOO

How to count the number of columns in the header of a csv file?

Just print NF and exit.

awk -F, '{print NF; exit}' file.csv

It should be pointed out that this is not safe for arbitrary csv as csv can quote commas within elements and awk will not handle that correctly.

How to add new column based on values of existing column in .txt file unix

Using awk:

awk 'NR==1{$7="V8";print;next}\
$6 == "Yes" {$7="2"};\
$6 == "No" {$7="1"}1' a.txt |column -t
  1. The first line print the V8 in the header
  2. If the value of 6th col: V7_Pheno is Yes, then $7 = "2"
  3. If the value of 6th col: V7_Pheno is No, then $7 = "1"
  4. column -t : for better formatting


Related Topics



Leave a reply



Submit