PDA

View Full Version : sed expression question



PryGuy
September 1st, 2010, 08:15 AM
Good day everyone!
Sorry to ask but how do I say in sed "if 'string1' does not exist add 'string2' to the end of the file once"?
Thank you in advance!

ghostdog74
September 1st, 2010, 08:41 AM
use awk for this so you can keep a counter/flag to signify found.



awk '/string1/{f=1}END{ if (!f) {print "string2"}}1' file

use the best tool for the job.

PryGuy
September 1st, 2010, 08:48 AM
Thanks, pal!

PryGuy
September 1st, 2010, 10:14 AM
Anyway, this construct does not work:

sed -i '/string1/!a\string2\' file

ghostdog74
September 1st, 2010, 11:49 AM
Anyway, this construct does not work:

sed -i '/string1/!a\string2\' file

this will not do what you required. This will supposedly add string2 after every line that string1 is not found.

PryGuy
September 1st, 2010, 12:00 PM
Sorry for being so nasty, but is there a way to do it in sed at all?

ghostdog74
September 1st, 2010, 12:27 PM
Sorry for being so nasty, but is there a way to do it in sed at all?

I will be nasty as well. I am going to keep asking you, why do you insist on doing that with sed, when you can easily do it with awk (or even other tools like grep)?



if grep -q "string1" "$file" ;then
echo "string2" >> $file
fi

this is so much easier !

spjackson
September 1st, 2010, 12:49 PM
Sorry for being so nasty, but is there a way to do it in sed at all?
I'll stick my neck out here. No, it is not possible to do what you want purely in sed. There are many appropriate tools for this task, but sed isn't one of them.

DaithiF
September 1st, 2010, 12:51 PM
well its not what sed was designed for, for sure, but as an exercise in masochism:

sed -n 'p;/string1/h;${x;/^$/astring2
}' testfile

spjackson
September 1st, 2010, 02:45 PM
well its not what sed was designed for, for sure, but as an exercise in masochism:

sed -n 'p;/string1/h;${x;/^$/astring2
}' testfile

That's not quite masochistic enough. This fails to output string2 if testfile is empty (0 bytes).

DaithiF
September 1st, 2010, 03:18 PM
true, but as you probably know sed can't do anything with 0-byte files. 0 bytes does not constitute a stream, so sed won't even get as far as executing a command. So if 0-byte files are a possibility then sed would never be the tool to use.

PryGuy
September 1st, 2010, 07:49 PM
Thank you, people!