Just a quick one – I had to edit an old PHP script that I wrote a while back to create calendar events. At the start of this file is a large array containing a number of letters which correspond to specific durations. As usual – I stuck with my one of the well known XKCD comics and decided that to update this file it was easier to learn a few new tricks (teach a man to fish and all that). In summary, I had to add to the file a list of formatted letters like
"N",
"N",
"N",
"L",
"L"
Each letter was repeated 3 times on recurring lines, and there was a total of 189 letters which had to be wrapped in quotation marks and have a comma at the end.
To begin with, I created a text file and entered in each line one character that would eventually become 3 lines. I then wrapped this up in AWK using the following one liner;
awk '{ print "\"" $0 "\","; print "\"" $0 "\","; print "\"" $0 "\","}' input.txt > output.txt
I know that docent look pretty, however its a one liner and it works. To start with,
print $0
will print the current line, so by prepending and appending the characters I needed, properly escaped, around that
$0
and repeating that 3 times I turned
N
L
R
into
"N", "N", "N", "L", "L", "L", "R", "R", "R",
for a total of 189 lines. I then moved this file to where I run my PHP script, and started VIM opening the two files at once. A quick press of
v
to select Visual Mode where I select the whole file, followed by a
:b 1
to move to the PHP script (the b stands for buffer, and the 1 is because that was the first file opened. 2 would be the seconds etc.) in VIM and a quick paste and I was almost done – I just had to remove the final comma
,
from the last array entry. I’m not good enough to have a bit of AWK work the last bit out – and the time spent implementing it would not be worth it.
AWK one liners, and AWK itself has never really been something I’ve used. In the past its been presented to me as a way to solve problems, but the solutions have been handed to me. This is the first time I’ve actively went hunting for a solution without asking for help – and even though its simple, I’m quite happy I managed to figure it out – even if it did take about 20 minutes of searching…
As a final note I’m also quite happy I managed this completely in the command line. No mice were used in the editing of this script!