in reply to Multiline regex for moving lines?

G'day bowei_99,

Your text is made up of a series of elements each consisting of a hash (#) followed by a variable number of characters which aren't hashes, i.e. "[#][^#]+".

The "last chunk", as you called it, doesn't need to be part of the replacement. Just match the first "#...", a pair of "#...", the "#..." you want to move; then move the 3rd capture before the 2nd:

$ perl -Mstrict -Mwarnings -le ' my $text = <<LIST; #EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=80000 80.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=400000 400.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=700000 700.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1500000 1500.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2500000 2500.m3u8 LIST $text =~ s{\A([#][^#]+)((?:[#][^#]+){2})([#][^#]+)}{$1$3$2}m; print $text; ' #EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=700000 700.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=80000 80.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=400000 400.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1500000 1500.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2500000 2500.m3u8

-- Ken