number snippets

How to extract numbers from a string in Bash scripts

Tagged bash, extract, number, regexp, rematch  Languages bash

To extract numbers from a string in Bash scripts you can use a bash feature called REMATCH. You don’t need grep, sed, or awk.

Add this to script.sh (remember to run chmod +x script.sh):

#!/usr/bin/env bash
string="COPY 23845\n3409"
if [[ $string =~ ^COPY[[:space:]]([0-9]+) ]]; then
  echo "Match: ${BASH_REMATCH[1]}"
else
  echo "No match"
fi

This will print 23845, but not 3409. Note that this example uses a capture group.

Converting a string to a number with CRC

Tagged conversion, crc, number, string  Languages ruby

CRC can be used to convert a string into a number:

require 'zlib'
integer = Zlib.crc32('snippet')
=> 2518453461
Zlib.crc32('cat')
=> 2656977832

The CRC algorithm is normally used to detect changes or errors in large chunks of data.