UNIX Regular expression to extract fields from a string based on Index position [duplicate] UNIX Regular expression to extract fields from a string based on Index position [duplicate] unix unix

UNIX Regular expression to extract fields from a string based on Index position [duplicate]


Try this regex:

/\d{4}(\d{4})/

Required data will be matched inside parentheses


echo "14150712.M" | cut -c5-8


If the positions are fixed, you can use Bash's substring parameter expansion:

 A="ABCDE"; echo ${A:1:2}

This prints BC. You can use this for example in a for A in *; do loop:

for A in *.M; do    NUMID=${A:4:4}    echo "We extracted \"${NUMID}\" from \"${A}\"."done