awk question: replacing "%d%s" by "%d %s"

Polytropon freebsd at edvax.de
Thu Jan 13 06:08:24 UTC 2011


On Thu, 13 Jan 2011 01:00:17 -0500, Tom Limoncelli <tal at whatexit.org> wrote:
> $ awk < data.txt > experiment.txt '{ num = $1 ; sub(/[^0-9]+$/, "",
> num) ; lets = $1 ; sub(/^[0-9]+/, "", lets); print num " " lets }' ;
> diff -cw control.txt experiment.txt
> $  # The above puts a space at the end of the first 3 lines.  If that
> is bad, try:
> $ awk < data.txt > experiment.txt '{ num = $1 ; sub(/[^0-9]+$/, "",
> num) ; lets = $1 ; sub(/^[0-9]+/, "", lets); if (length(lets)) { print
> num " " lets } else { print num } }' ; diff control.txt experiment.txt
> $

Thanks for your inspiration! I concluded that it is
a possible way to split the string into two parts:
not-numbers (letters) and numbers, and then recombining
them in the desired way.

Here's my code:

	if(match(nr, "[a-z]")) {
		z = nr;
		gsub(/[^0-9]+$/, "", z);
		b = nr;
		gsub(/[0-9]/, "", b);
		nr = sprintf("%s %s", z, b);
        }

First catch all nr's that have a letter in it, then
remove the letters in one copy, then the numbers in
another one, and finally overwrite nr with the proper
recombination that includes the space.

Works as intended, FULLY. Thanks!



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list