sed one-liner: search text in file and replace it. if not present, insert it
As indicated in the subject, I want to search a text.
If the text is present I want to replace it. But if the text is not present, I want to insert it after first line and before last line. Searched text is:CleanCache "*"; Where * can be anything. Example: CleanCache "false"; -> CleanCache "true"; If CleanCache "false"; is not present, only insert CleanCache "true"; after first line and before last line. |
Hi,
although it is possible to do all this with one sed instruction I do not think that this would be the best solution in this case. You would make a mess in the Hold buffer and then by the end would try to modify it with a more or less complicated regex. Try this instead Code:
sed -n '/pattern/ q 99' infile FWIW, here is one possible solution with just one sed. However, this does not *really* qualify as a one-liner. Code:
# not recommended |
use awk
Code:
#! /bin/bash |
Here is an awk alternative:
Code:
awk '/CleanCache.*false/{save = "Cleancache \042true\042";a=1;next}g{print save}{save=$0;g=1}END{if(a)print save;else print "Cleancache \042true\042\n" save}' file |
Quote:
|
My bad :redface: ... I like yours then :)
|
Thanks
Many many thanks to all for your effort.
@crts, @ghostdog74: I really need some art of one liner… Because I don’t want to create first a script and after the script has finished, delete the script… Isn it a little redundant and unnecessary? To help a little: The file I want to edit is "/root/.synaptic/synaptic.conf" and what I must insert is the following: CleanCache "true"; AutoCleanCache "true"; delHistory "1"; Its a bit of non-graphical tuning of the synaptic-app! Cheers & thanks! *Thumbs up**Thumbs up* |
I am not sure I see the point of this then as it would be a one time edit, why not just open with your favourite editor and do the job?
|
Quote:
you can put the last 'sed' script in one line in the console and will make the changes you need. You just need to modify 'pattern/newpattern' accordingly to what you want. I said that it does not qualify as a one-liner just because I personally consider a sed statement as one liner if it does not exceed five commands. If you add the -i.bak option you won't even have to redirect the output to a new file and it will also make a backup of the processed file. |
All times are GMT -5. The time now is 04:41 PM. |