Home > Software design >  Delete every number after 14 digit count
Delete every number after 14 digit count

Time:04-04

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

CodePudding user response:

Using sed

$ sed 's/[0-9]//15g' file
12345678912345
34543234567654
34543234567651
34543234567652
34543234567653

CodePudding user response:

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

CodePudding user response:

If you want to extract only numbers, how about

grep -Eo '^[0-9]{14}' file >res1.csv

CodePudding user response:

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
  • Related