On 28 June 2011 13:06, Glenn Cogle <[email protected]> wrote:
> Hi all sed gurus (& wannabes like me),
>
> Wanting to `sed` beyond my present understanding;
>
> echo abcdefghijklmnopqrstuvwxyz | sed 'keep first 5 chars, then append a Z
> to every fourth char thereafter, and keep the leftovers too'
>
> ie
>
> abcdefghiZjklmZnopqZrstuZvwxyZz
>
> I think sed would be capable of this - but haven't proven it yet.
>
echo abcdefghijklmnopqrstuvwxyz | perl -ple 'substr( $_, 5 ) =~ s/(.{4})/$1Z/g;'
abcdefghiZjklmZnopqZrstuZvwxyZz
^ works, but I'd advise against' relying wholly on oneliners.
Also, at present, that works linewise, ie: each line will start over,
skip 5 characters, etc.
If you wanted it to work on the entire file like that, it would
require a little modification.
Code Expansion:
-ple 'foo'
is shorthand for
# ARGV is either a stream of all input from all files listed as arguments,
# or the contents of STDIN
while( defined ( $_ = <ARGV> ) ) {
chomp $_ # trim \n from end.
foo # <-- code goes here
print $_, "\n";
}
substr( $_, 5 ) =~
does an in-place modification of $_ , allowing the right hand side of
the =~ operator to modify all characters except the first 5.
=~ s/(.{4})/$1Z/g
walks over the string an injects a 'Z' after each 4th character. (
Capture a group of 4 characters, replace it with that captured group
followed by a Z, repeat )
--
Kent
perl -e "print substr( \"edrgmaM SPA NOcomil.ic\\@tfrken\", \$_ * 3,
3 ) for ( 9,8,0,7,1,6,5,4,3,2 );"
http://kent-fredric.fox.geek.nz
_______________________________________________
Linux-users mailing list
[email protected]
http://lists.canterbury.ac.nz/mailman/listinfo/linux-users