[mdlug] GNU sed weirdness

Aaron Kulkis akulkis00 at gmail.com
Sun Jan 24 03:23:14 EST 2010


Jeff Hanson wrote:
> With GNU sed on Ubuntu 8.04 I'm wrote a simple script that takes in a
> Windows full-path file listing and changes it to a Windows 7-zip
> compression batch file.  It uses back references get the parent
> directory path and filename.  There are several files that have the
> same name but with different extensions and I just want to put all the
> ones that match by filename into the same 7z file.  I wanted to use
> variables for the 7-zip path, target directory, and compression
> options.  Because of spaces in the directory and file names I need to
> embed quotes.  To keep the sed command from getting really ugly I
> split it up into a single-quoted search, double-quoted (because of
> variable expansions) replacement for the variables followed by
> single-quoted replacement for the back references.  The back
> references \1 holds the directory path and \2 holds the filename
> without extension.  What I though was the correct form looks like
> this:
> 
> sed -n 's/\(.*\)\\\(.*\)\.idx/'"\"$compress_exe\" $compress_opts
> \"$target_dir\\"'\2'".$compress_ext"'\" \"\1\\2.*\"/p' $1
> 



> Broken up:
> sed -n 's/\(.*\)\\\(.*\)\.idx/'
> "\"$compress_exe\" $compress_opts \"$target_dir\\"
> '\2'
> ".$compress_ext"
> '\" \"\1\\2.*\"/p' $1

If in doubt, break the problem down instead of trying to do it
all in one fell swoop as a "one-liner"

One liners are one of the major reasons (the other
being the character set) for APL being a "write-only"
(i.e. unreadable.) language.

Perl suffers from the same problem -- too many perl
coders try to write programs to have the fewest number
of newlines rather than being readable (and hence,
debugable and maintainable and debugable.  Did I
mention debugable?).

You're hitting the outer-edge of sed-ness.
But you are smack dab in the middle of awk-ness.

So, I would suggest redoing this in AWK instead.

(I.e, rather than trying to beating your head trying
to use a pocket knife to whittle a piece of wood into
a smooth, round, baseball bat -- something techinically
possible, but very difficult, just put your piece of
wood on a lathe, and get the job done).

Excellent tutorials here:
<http://cm.bell-labs.com/7thEdMan/>

Volume 1 is the man pages we all know and love (sometimes)
Volume 2a and 2b are the tutorial sections.
<http://cm.bell-labs.com/7thEdMan/vol2/awk>

Download the PDF or postscript files to your
computer, and keep them for reference.
http://cm.bell-labs.com/7thEdMan/bswv7.html

PDF:
<http://cm.bell-labs.com/7thEdMan/v7vol1.pdf>
<http://cm.bell-labs.com/7thEdMan/v7vol2a.pdf>
<http://cm.bell-labs.com/7thEdMan/v7vol2b.pdf>

Postscript:
<http://cm.bell-labs.com/7thEdMan/v7vol1.ps.gz>
<http://cm.bell-labs.com/7thEdMan/v7vol2a.ps.gz>
<http://cm.bell-labs.com/7thEdMan/v7vol2b.ps.gz>



More information about the mdlug mailing list