This single-command BASH script file is difficult to understand, so I want to write a comment for each of the actions:

grep -R "%" values* \
| sed -e "s/%/\n%/" \
| grep "%" \
| grep -v " % " \
| grep -v " %<" \
| grep -v "%s" \
| grep -v "%d" \
| grep -v "%1$s"

I would hate having to duplicate lines, or having each comment far away from the line it applies to.
But at the same time BASH does not seem to allow "in-line" comments.

Any elegant way to solve this problem?

link|improve this question

71% accept rate
There's a bug in it, regardless of the comments. – Ignacio Vazquez-Abrams Jan 28 '11 at 5:47
Ignacio, thanks for your feedback! I could not spot it yet, though... If you're interested, this script is used to spot malformed string replacement patterns in Android localization files, and it seems to work, so far. Any improvement is welcome! – Nicolas Raoul Jan 28 '11 at 5:55
1  
The last grep has a shell substitution in double quotes, which will replace it with whatever the shell has in that variable (which is probably nothing, given the specific variable name). Replace with single quotes to fix. – Ignacio Vazquez-Abrams Jan 28 '11 at 6:03
Indeed! Ignacio, thanks a lot! – Nicolas Raoul Jan 28 '11 at 6:14
1  
For the script at hand, egrep would be better and faster. egrep -v ' % | %<|%s' – bukzor Mar 9 '11 at 4:33
feedback

2 Answers

up vote 4 down vote accepted

Put the pipes at the end of line with the comments after it:

$ echo 'foo' |
sed 's/f/a/' | # change first f to a
sed 's/o/b/' | # change first o to b
sed 's/o/c/'   # change second o to c
abc
link|improve this answer
feedback

If you happen upon this question while looking to comment a non-pipeline multiline command:

$ echo 'foo' |
sed -e 's/f/a/' `: # change first f to a` \
    -e 's/o/b/' `: # change first o to b` \
    -e 's/o/c/' `: # change second o to c`

Unless you're doing something really perverse like automating commenting, I can't see a reason to prefer this over Mikel's answer for a pipe, but if you really wanted to:

$ echo 'foo' |
sed 's/f/a/' | `: # change first f to a` \
sed 's/o/b/' | `: # change first o to b` \
sed 's/o/c/'   `: # change second o to c`

or:

$ echo 'foo' |
sed 's/f/a/' `: # change first f to a` |
sed 's/o/b/' `: # change first o to b` |
sed 's/o/c/' `: # change second o to c`

Source: http://unix.derkeiler.com/Newsgroups/comp.unix.solaris/2005-07/0991.html

link|improve this answer
Very nice — thanks for pointing this out! – Brandon Rhodes Jul 28 '11 at 4:08
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.