Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have two things I need to check a text file for:

  1. If it is tab-delimited
  2. If it has exactly 8 columns

How can I check those things and show an error message if either is false?

share|improve this question

migrated from stackoverflow.com Sep 12 '11 at 13:10

This question came from our site for professional and enthusiast programmers.

A plain text file with no tab characters at all could well be a tab-delimited file that happens to have one field per line. – Keith Thompson Sep 12 '11 at 8:25
Is this really tab delimited, or is it merely tab separated? – tchrist Sep 12 '11 at 18:12

One solution is to use awk:

awk -F "\t" 'NF != 8' data.txt

This command will print out those lines in the file data.txt which does not have 8 fields.

share|improve this answer

You could use a perl oneliner, like so:

perl -ne '(s/\t//go)==7 or die "Not tabdelimitedand 8-columned"' t.txt

Which will exit with an error message if the file does not conform. To allow further (bash) scripting:

if perl -ne '(s/\t//go)==7 or exit -1' t.txt
    echo correct format
    echo unexpected format
share|improve this answer
ct=($(sed -re 's/[^\t]//g' "$file" | expand -t1 | wc -l -c -L))

if (( ((ct[0] * 8) == ct[1]) && (ct[2] == 7) )) ;then
    echo "file contains 8 tab-delimited fields on every line"
    if (( ct[1] == ct[0] )) ;then
        echo "file does not contain any tab-delimiters"
        echo "file contains tabs, but does not have 8 fields on every line"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.