bash: inserting new line in file if...
Hi,
I don't pretend anyone to do my work, but I am wondering which would be the best way to insert a row into a sorted text file, if the first field changes: From: 11111,aaaa,bbbb 11111,ccccc,dddd 22222,aaaa,bbbb To: 11111,aaaa,bbbb 11111,ccccc,dddd -new text inserted here- 22222,aaaa,bbbb The condition is that 11111 changed to 22222 (the purpose is adding middrules to a latex input table) Thanks a lot! |
Hello and Welcome to LinuxQuestions,
Is this by any chance homework? It looks like it is. Anyway, have a look at this Sed tutorial, it can be used to do what you need, amongst other tools. LQ users are at their best solving problems but are not in the habit of, like you saying do the work for you. So post what you've tried and we'll take it from there. Enjoy the forums and Linux. Kind regards, Eric |
Could you provide some actual lines of input and desired output, instead of an idea. Using sed and awk the description needs to exact. For example, is the first column always 5 characters in width? If not, I would have had to convert the commas to spaces or tabs for the uniq command to process just the first column.
You could use `uniq' to select changes in the first column. Pipe the results to sed to 1) delete the first line 2) generate a sed script with lines of the form: /22222,aaaa,bbbb/i\ inserted line /33333,abcd,defg/i\ inserted line Then to perform the conversion run the sed script: sed -f inserts.sed input.tex >output.tex Code:
> cat testfile3 |
Quote:
Old Linux user, but new to this forum ;) Quote:
Code:
FILE=1001 |
A simple awk alternative:
Code:
awk -F, '!_[$1]++ {print "---------------"}1' 1001 > 1002 |
colucix: Your solution is much more concise than mine:
Code:
sed -f <(uniq -w5 testfile3 | sed '1d;s#.*#/&/i\\\nsample-test#' ) testfile3 |
Just can take my hat off.
How amazing is being able to summarize in just one line of code what I need to do in more than ten! Thanks to all of you. |
If only looking to add after first change with the awk you may wish to throw a 'NR > 1 &&' at the start :)
|
All times are GMT -5. The time now is 08:47 PM. |