mac_online
mac_online

Reputation: 370

find records longer/shorter than a particular col

this is my file: FILEABC.txt

Name|address|age|country
john|london|12|UK
adam|newyork|39|US|X12|123
jake|madrid|45|ESP
ram|delhi
joh|cal|34|US|788

I wanted to find the the header count in the file. so i've this command

cat FILEABC.txt | awk --field-separator='|' '{print NF}' | sort -n |uniq -c

the result i get for this cmd is

cat FILEABC.txt | awk --field-separator='|' '{print NF}' | sort -n |uniq -c

  1 2
  3 4
  1 5
  1 6

My requirement is that, how do i find those records that have only 2 fields, 4 fields and so on from my file. for ex,

if want to see the records having only 2 col:

 ram|delhi

if want to see rec's having more than 4 col:

adam|newyork|39|US|X12|123 

Upvotes: 1

Views: 153

Answers (3)

making_code
making_code

Reputation: 159

you can also use grep to filter 2-columed records:

grep '^[^|]*|[^|]*$' FILEABC.txt

It will output:

ram|delhi

Upvotes: 1

Akshay Hegde
Akshay Hegde

Reputation: 16997

Using awk, variable NF gives total number of fields in record/row, by default awk use single space as field separator, if you alter FS, it will calculate NF based on field separator mentioned, so what you can do is

awk -v FS='|' 'NF==2' infile

Which is same as

# Usual Syntax : awk 'condition { action }' infile

awk -v FS='|' 'NF==2{ print }' infile

For more than 4 fields,

awk -v FS='|' 'NF > 4' infile

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133680

If you want to only print the records which have 2 fields then following may help you in same.

awk -F"|" 'NF==2'   Input_file

For any kind of records if you need a line which has more than 4 fields then change above condition to NF>4 or you need line which have more than 5 fields eg--> NF>5

Explanation: BY doing -F"|" I am making sure field separator is pipe here, then NF is an awk out of the box variable which defines the TOTAL number of fields in a line, so as per your request checking if number of fields are more than 2 here, if this condition is TRUE then print the current line(where I have NOT written print because awk works on method of condition and action, so if condition is TRUE here I am not mentioning any action and by default action print will happen for that line).

Upvotes: 1

Related Questions