#!/bin/perl -w use strict; foreach( ) { s{^\d+_ # start then number(s) then _ ((?:\D*(?:\d(?!\d*_))?)*) # non_digits then optionnaly # a digit _not_ followed by digits and _ # repeat, rince... \d+_ # the second digit _ sequence (.*)} # the rest of the string {$1$2}x; print; } __DATA__ 1_abc/2_deg/bla_30_31_blah 1_ab1c/2_deg/bla_30_31_blah 1_ab1c/22_deg/bla_30_31_blah 1_a2b33c/22_deg/bla_30_31_blah a_ab1c/b_deg/bla_30_31_blah