Zombo
Zombo

Reputation: 1

Ignore empty fields

Given this file

$ cat foo.txt
,,,,dog,,,,,111,,,,222,,,333,,,444,,,
,,,,cat,,,,,555,,,,666,,,777,,,888,,,
,,,,mouse,,,,,999,,,,122,,,133,,,144,,,

I can print the first field like so

$ awk -F, '{print $5}' foo.txt
dog
cat
mouse

However I would like to ignore those empty fields so that I can call like this

$ awk -F, '{print $1}' foo.txt

Upvotes: 1

Views: 441

Answers (5)

Zombo
Zombo

Reputation: 1

$ awk '{print $1}' FPAT=[^,]+ foo.txt
dog
cat
mouse

Upvotes: 1

Vijay
Vijay

Reputation: 67319

awk -F, '{gsub(/^,*|,*$/,"");gsub(/,+/,",");print $1}' your_file

tested below:

> cat temp
,,,,dog,,,,,111,,,,222,,,333,,,444,,,
,,,,cat,,,,,555,,,,666,,,777,,,888,,,
,,,,mouse,,,,,999,,,,122,,,133,,,144,,,

execution:

> awk -F, '{gsub(/^,*|,*$/,"");gsub(/,+/,",");print $1}' temp
dog
cat
mouse

Upvotes: 0

Sidharth C. Nadhan
Sidharth C. Nadhan

Reputation: 2253

perl -anF,+ -e 'print "$F[1]\n"' foo.txt
dog
cat
mouse

this is no awk but you will get to use 1 instead of 2.

Upvotes: 0

fedorqui
fedorqui

Reputation: 290515

You can delete multiple repetition of a field with tr -s 'field':

$ tr -s ',' < your_file
,dog,111,222,333,444,
,cat,555,666,777,888,
,mouse,999,122,133,144,

And then you can access to dog, etc with:

$ tr -s ',' < your_file | awk -F, '{print $2}'
dog
cat
mouse

Upvotes: 0

Guru
Guru

Reputation: 17054

You can use like this:

$ awk -F',+' '{print $2}' file
dog
cat
mouse

Similarly, you can use $3, $4 and $5 and so on.. $1 cannot be used in this case because the records begins with delimiter.

Upvotes: 4

Related Questions