Length of each line.

Hi All,

I have 5 different type of lines in my file TEST1.txt

I need to perform the following conditions in the file

If first 4 characters of the line is 1010, then length of the line should be 132
If first 4 characters of the line is 9142, then length of the line should be 41
If first 4 characters of the line is 1011, then length of the line should be 250
If first 4 characters of the line is 9999, then length of the line should be 70
If first 4 characters of the line is 4949, then length of the line should be 152

I am using cut, but it is taking very long time to execute the entire file.

Can anyone help on this.
Thanks in advance

What is the action you want to do if a particular condition is met?

if the condition not met, it should throw the error mesg with line number in seperate file.

i can give you an idea..
first read the file line by line using while loop
then find the length
according to line length write switch case statement where you can check fro first 4 characters
this should take less time..

Apply the logic :

awk '{
 if (!(/^1010/ && length($1)==132)) print NF" "$0>>"/tmp/file_out" ;
 if (!(/^9142/ && length($1)==41)) print NF" "$0>>"/tmp/file_out" ;
 if (!(/^1011/ && length($1)==250)) print NF" "$0>>"/tmp/file_out" ;
 if (!(/^9999/ && length($1)==70)) print NF" "$0>>"/tmp/file_out" ;
 }'  filename

The logic seems wrong to me, it will print basically every line because some of the conditions will be true for all lines.

Perhaps this is closer to what you want.

awk '/^1010/ { if (length($0)==132) next }
/^9142/ { if (length ($0) == 41) next }
/^1011/ { if (length ($0) == 250) next }
/^9999/ { if (length ($0) == 70) next }
/^4949/ { if (length ($0) == 152) next }
{ print NF }' filename >/tmp/file_out

thanks for pointing it out. :stuck_out_tongue: We need to use the else to tackle it.

Actually I just refactored it for unrelated reasons ("next" is easier to type five times than "print NF" and if you want to print the whole line instead it's only one place to change). The fundamental problem is that !(/^9999/ && 1) is true for files which do not match /^9999/.