Monday, August 13, 2012

Newlining

As a budding vi, bash, sed, and general Unix-command-line power user, I'm often pleased at the magical powers that these awesome tools provide. There are a few annoyances inherent to this more minimal environment, though, and one of them has been newline manipulation.

The newline is this mystical, elusive, not-always-obvious-on-terminal, cross-platform-incompatible character that permeates a darn large majority of text files out there. It is a natural and almost global exception case for terminal display and for most text-based manipulation commands. As such, I often find myself wanting to collapse or insert newlines, unable to do so in command line, and unelegantly reverting to TextEdit or other GUIs temporarily just to get the job done. I've always trusted that command line provides appropriate tools to deal with newlines, but I have not set out to learn them just yet.

But today I learned one pretty nifty way of dealing with it in vi. I was trying to convert this command I created ad-hoc'ly:


declare -a f=$(cat robots2002_segs.txt); n=9; echo ${#f}; while (( n < ${#f[@]} )); do echo ${f[$n]}; echo ${f[ (( $n + 3 )) ]}; n=$((n+4)); done

into a nicely delineated:

declare -a f=$(cat robots2002_segs.txt)
n=9
echo ${#f}
while (( n < ${#f[@]} ))
        do echo ${f[$n]}
        echo ${f[ (( $n + 3 )) ]}
        n=$((n+4))
done


Seems easy enough, right? Replace the "; " strings with a newline, and I'm (almost) done! But alas, how do I tell vi's substitute (:s) command that I want to represent the newline character, when the key I use to represent it, [ENTER], only tells vi to execute the command?

Well, today I found out! Command down here:

:%s/; /CtrlVCtrlM/g

Break-down:

  • : begins the vi command
  • % tells it to apply this command on all lines of the file (unnecessary in this example)
  • s stands for substitute-command
  • ; / text to be replaced
  • CtrlvCtrlM The magic! Vi's representation for a newline, as far as I can tell.
  • /g Do it as many times as you can.


And done! And then I spent 20 minutes writing the blog post, when doing the whole thing manually would've taken me no more than 20 seconds. Oh, the joys of obsessive optimization!

Credits: (Thanks Mr. Boothe!)
http://www.computing.net/answers/unix/vi-ex-substitute-with-newline/6485.html

No comments:

Post a Comment