Please have a look at my mind-breaker.
I’d stuck in shrinking with regex some long path, like this:
/12345/123456/1234/123/12/1/1234567/13245678/123456789/1234567890
I’d like to transform this path to the following form:
/123/123/123/123/12/1/123/123/123/123
each “directory” in a path abbreviates to only 3 first characters
LONG_PATH="/12345/123456/1234/123/12/1/1234567/13245678/123456789/1234567890"
perl -pe "s#/(.{1,3})[^/]*?(/|$)#/\1\2#g" <<<$LONG_PATH
/123/123456/123/123/12//1234567/132/123456789/123
sed -E "s#/(.{1,3})[^/]*?(/|$)#/\1\2#g" <<<$LONG_PATH
/123/123456/123/123/12//1234567/132/123456789/123
I have tried also:
perl -pe "s,/(.)(.)?(.)?[^/]*+,/\1\2\3,g" <<<$LONG_PATH
/123/123/123/123/12//123/132/123/123
and many another, no “luck” – I still have no idea about.
Please point me a right way to success.
Match up to three non-slash characters and capture them. Then match the rest until the next slash. Replace by the capture:
There is no need for ungreediness or anything here, because the negated character class is mutually exclusive with the
/or$.EDIT: Although you seem to know this I should probably clarify for future visitors that this will work with either
perl -pe...orsed -E...as you have used it in your question. The regex could also be used as is withsed -r.... If you leave out the-Eor-roption, then (as usual) you will need to escape both the parentheses and curly brackets:Note also as ikegami points out that in Perl you should rather use
$1in the replacement than\1.