Lazyweb - awk
May. 15th, 2009 04:29 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
A bash script I use ends by displaying a line it wants you to add to another file. It would obviously be easier if the script did this itself. As the line will be somewhere in the middle of the file, just using '>>' to append it is no good.
Somewhere :) I have (or had) The AWK Programming Language and my Google skills are enough to be reminded that:
will add 'my new line' after 'NEW STUFF HERE'.
Now, 'my new line' needs to have a number in it that is different to all the other such lines (it's an array index).
Can someone remind me of a good way to do that? The line count of the entire file prior to adding the line would be fine, for example.
Somewhere :) I have (or had) The AWK Programming Language and my Google skills are enough to be reminded that:
awk '/NEW STUFF HERE/ {print;print "my new line";next}1' test-file
will add 'my new line' after 'NEW STUFF HERE'.
Now, 'my new line' needs to have a number in it that is different to all the other such lines (it's an array index).
Can someone remind me of a good way to do that? The line count of the entire file prior to adding the line would be fine, for example.
(no subject)
Date: 2009-05-15 08:57 pm (UTC).. FNR = the line number, effectively.
So you get
Then all you have to do is remember you have to write it to a temporary file and move over the original rather than writing to the original. (A good way to delete your original!)
(no subject)
Date: 2009-05-15 09:39 pm (UTC)(no subject)
Date: 2009-05-15 11:12 pm (UTC)I don't know awk well enough so have an over-engineered perl solution instead
Date: 2009-05-15 09:31 pm (UTC)If the search patter appears twice then the text gets inserted after the first, or you can edit the obviously named variable to have it inserted after every occurrence. You didn't state what format the numbers take so I guessed. It shouldn't be too hard to change to suit your requirements. One caveat - it doesn't check for duplicate index values.
(no subject)
Date: 2009-05-16 09:44 am (UTC)This isAmongst the reasons I like the command line so much is that there are so many ways of doing something, almost all of which are easier than doing the same thing the WIMPy way, and some of them are so elegant.I'm not sure of the strict requirements for the numbers, I just know that natural numbers work and they don't need to be sequential (although my second solution will make them so) or start at any number in particular. Neither does mine :)