Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

3  
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
add comment

3 Answers 3

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
add comment

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
then
    echo correct format
else
    echo unexpected format
fi
share|improve this answer
add comment
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"
else 
    if (( ct[1] == ct[0] )) ;then
        echo "file does not contain any tab-delimiters"
    else
        echo "file contains tabs, but does not have 8 fields on every line"
    fi
fi
share|improve this answer
add comment

Your Answer

 
discard

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