Bash substring not working how it should

Hi All,
I have a text file. The file contains some records out of which I wish to recover first 6 digits and last 4 digits.


$cat text.txt
111111****1111
222222****2222
333333****3333
444444****4444
555555****5555

I wrote a small shells script to locate records but it's not working.

while read inputline;
do
  card=$(echo "$inputline" | cut -d "," -f 1)
  D6=${card:1:6}                               ## last 4 digits 
  D4=${card:10:4}                             ## first 6 digits 
	if ! [[ "$D6" =~ ^[0-9]+$ ]]  || ! [[ "$D4" =~ ^[0-9]+$ ]]; then
	 echo "Inserted Card Number " $card $D6 $D4;
	      echo $count;
	else
	    echo "Card $card is invalid."
	fi
done < "$filename"

Open in new window


I get following results
D4 : 1111
D6 : 11111*
 
D4 : 2222
D6 : 22222*

Even if I change the line "D6=${card:1:6}"  to "D6=${card:0:6}"   there is no improvenment at all. What am I doing wrong?


Thanks in advance.
crazywolf2010Asked:
Who is Participating?
 
farzanjCommented:
Try this:


#!/bin/bash

filename=XXXX

while read inputline;
do
  card=$(echo "$inputline" )
  D6=${card:0:6}                               ## last 4 digits
  D4=${card:10:4}                             ## first 6 digits
    if [[ "$D6" =~ ^[0-9]+$  ||  "$D4" =~ ^[0-9]+$ ]]; then
     echo "Inserted Card Number  $card $D6 $D4";
          echo $count;
    else
        echo "Card $card is invalid."
    fi
done < "$filename"

Open in new window

0
 
farzanjCommented:
Try ${card:0:5}
0
 
farzanjCommented:
Sorry,

${card:0:6} should get the right result
0
 
farzanjCommented:
The other problem is : ! in the if statement.  Do you really need that.

I ran your script and found the results as expected using ${card:0:6} and removing ! with the if statement
0
 
crazywolf2010Author Commented:
Great work
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.