Easier way to toggle comments?

18 views
Skip to first unread message

Todd A. Jacobs

unread,
Apr 2, 2011, 7:38:31 PM4/2/11
to FOSS Scripting
I'm using the following to toggle lines on and off in my Ruby .gemrc
file:

toggle-rdoc () {
local FILE="$HOME/.gemrc"
{ rm $FILE &&
awk '/^#/ {sub(/^#/, "", $0); print; next};
/^[^#]/ {sub(/^/, "#", $0); print}' > $FILE
} < $FILE
cat $FILE
}

It works, but it just seems like there ought to be an easier way. I
couldn't get it to work with sed for some reason; it seems to need
some serious branching to work at all in sed. Here's what I tried in
sed:

alias toggle-rdoc='sed -ri "/^#/{ s/^#// }; s/^([^#])/#\1/"
~/.gemrc; cat ~/.gemrc'

but the results are always the same; no toggling happens at all.
*sigh*

Can anyone think of a more elegant solution for this problem?

Mëa Cúlpa

unread,
Oct 17, 2011, 12:23:58 AM10/17/11
to foss-sc...@googlegroups.com
Todd A. Jacobs <nos...@codegnome.org>:

Why not use printf instead of sub?

awk ' /^[^#]/ {printf("#%s\n", $0)}'

Regarding elegance,

A full-featured awk script is elegant enough.
What else do you want if you have a line-based, regex-powered,
C-flavoured Just-In-Time interpreter like AWK??


--
- Mëa Cúlpa - infernoxu at gmail dot com
- http://ucarenya.com/

Stephane CHAZELAS

unread,
Oct 17, 2011, 4:49:45 AM10/17/11
to foss-sc...@googlegroups.com
2011-10-17, 04:23(+00), Mëa Cúlpa:

> Todd A. Jacobs <nos...@codegnome.org>:
>> I'm using the following to toggle lines on and off in my Ruby .gemrc
>> file:
>>
>> toggle-rdoc () {
>> local FILE="$HOME/.gemrc"
>> { rm $FILE &&
>> awk '/^#/ {sub(/^#/, "", $0); print; next};
>> /^[^#]/ {sub(/^/, "#", $0); print}' > $FILE
>> } < $FILE
>> cat $FILE
>> }
>>
>> It works, but it just seems like there ought to be an easier way. I
>> couldn't get it to work with sed for some reason; it seems to need
>> some serious branching to work at all in sed. Here's what I tried in
>> sed:
>>
>> alias toggle-rdoc='sed -ri "/^#/{ s/^#// }; s/^([^#])/#\1/"
>> ~/.gemrc; cat ~/.gemrc'
>>
>> but the results are always the same; no toggling happens at all.
>> *sigh*
>>
>> Can anyone think of a more elegant solution for this problem?
>>
>
> Why not use printf instead of sub?
>
> awk ' /^[^#]/ {printf("#%s\n", $0)}'
[...]

sed -e 's/^#//;t' -e 's/^/#/'

Or

awk '{print /^#/ ? substr($0,2) : "#" $0}'

--
Stephane

Reply all
Reply to author
Forward
0 new messages