0

I am reading numbers from a file. Then counting the total digits in that number and trying to delete all the digits after 14 digits count. In my current logic I was only able to reduce one digit if it exceeds 14 digit count. I am trying to eliminate all other digits once it reaches 14 digit count.

file:

numbers
123456789123454
3454323456765455
34543234567651666
34543234567652
34543234567653

logic.sh:

while read -r numbers  || [[ -n "$numbers" ]]; do
    digit_number="${imei//[^[:digit:]]/}"
    echo "digit of number: ${#digit_number}"
    if ((${#digit_number} > 14)); then
        modified=${numbers%?}
        echo $modified > res1.csv
    else
        echo $numbers >res1.csv
    fi
done <$file

expected output

12345678912345
34543234567654
34543234567651
34543234567652
34543234567653
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
coder
  • 61
  • 5

4 Answers4

3

Using sed

$ sed 's/[0-9]//15g' file
12345678912345
34543234567654
34543234567651
34543234567652
34543234567653
HatLess
  • 5,048
  • 4
  • 8
  • 28
1

You can use cut for that task:

╰─$ echo "12345678901234567890" | cut -c 1-14
12345678901234

There is also no need to read the file line by line:

╰─$ echo "numbers                  
123456789123454
3454323456765455
34543234567651666
34543234567652
34543234567653" > file

╰─$ cat file | cut -c 1-14 > output

╰─$ cat output                     
numbers
12345678912345
34543234567654
34543234567651
34543234567652
34543234567653
mashuptwice
  • 617
  • 2
  • 16
1

If you want to extract only numbers, how about

grep -Eo '^[0-9]{14}' file >res1.csv
tripleee
  • 158,107
  • 27
  • 234
  • 292
0

Updated your script.

while read -r numbers  || [[ -n "$numbers" ]]; do
     DIGITS=$(echo $numbers | cut -c 1-14)
     echo $DIGITS >> res1.csv
done

Now output:

12345678912345
34543234567654
34543234567651
34543234567652
34543234567653
Sergei
  • 183
  • 1
  • 5