Unix command to get number of lines in a CSV file

I have to get the count of lines from incoming CSV files.

I have used the following command to get the count.

wc -l filename.csv

Consider a file coming with 1 record, I am getting some files with a \* at the start, and for those files if I issue the above command it returns count of 0.

Why is \* at the beginning of the file not register as a counted line and is there a work around?

6

2 Answers

A trick to ensure that also non-terminated lines are counted may be:

cat filename.csv | xargs -l echo | wc -l

This seems to count all non-empty lines, but skips empty lines.

Please note that is is rather ineffective, but that is probably not a problem for occational use.

Another possibility, counts all lines including non-terminated last line:

awk '{n+=1} END {print n}' filename.csv

Tested on RHEL 6.2. YMMV.

1

wc will report 0 for files with only one line and no trailing newline. Maybe your one-record csv files are like this? You can look for trailing newlines with hexdump, e.g.:

hexdump -C fn.csv

Look for ascii code 0a at the end.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like