Search code examples
bashgrepcut

How can I extract the 11th and 12th characters of a grep match in Bash?


I have a text file called temp.txt that consists of 3 serial numbers.

AB400-251429-0014
AA200-251429-0028
AD200-251430-0046

The 11th and 12th characters in the serial number correspond to the week. I want to extract this number for each unit and do something with it (but for this example just echo it). I have the following code:

while read line; do
   week=` grep A[ABD][42]00 $line | cut -c11-12 `
   echo $week
done < temp.txt

Looks like it's not working as cut is expecting a filename called the serial number in each case. Is there an alternative way to do this?


Solution

  • The problem is not with cut but with grep which expects a filename, but gets the line contents. Also, the expression doesn't match the IDs: they don't start with S followed by A, B, or D.

    You can process lines in bash without starting a subshell:

    while read line ; do
        echo 11th and 12th characters are: "${line:10:2}".
    done < temp.txt
    

    Your original approach is still possible:

    week=$( echo "$line" | grep 'S[ABD][42]00' | cut -c11-12 )
    

    Note that for non matching lines, $week would be empty.