Sed/grep: check if line exists, if not add line?

Hello,
I'm trying to figure out how to speed up the following as I want to use multiple commands to search thousands of files.

is there a way to speed things up?

Example I want to search a bunch of files for a specific line, if this line already exists do nothing, if it doesn't exist add it below

So far I have

searchString="PortSystem 1.0"

addString="PortGroup user 1.0"
file="Portfile"
export -f doStuff
find . -depth  -name ${file} -type f -exec bash -c 'doStuff "$0"' {} \;

function doStuff(){
if grep -Fxq "$searchString" ${1:-} 
then   
sed '/$searchString/s/.*/&\n$addString' ${1:-}  
fi  
return 0
}

Thanks

What line do you search for,
searchstring or addstring or both?
What to do in which case?
Your function looks only for searchstring and adds addstring behind it.
But the subject and text says a string should be added if something does NOT exist.

1 Like

Speeding up could be done by NOT executing a bash shell with command / function for every single file name found. Have find write all file names to a temp file, and read that in a while loop, callig the function from within - if a function is needed at all. grep ping and sed ding the same file means read / process it twice - use sed only to process it once. And, on top of what MadeInGermany already stated, you need to specify the position where to add the addstring if searchstring is missing, unless that were end-of-file.

1 Like

Thanks. Inside the sed command is '\n' which inserts a new line. So I really don't get your point, the string is added on a new line if the searchString is not found. DId I misunderstand your statement?

I think
grep -Fxq "$searchString"
is true if $searchString is found.
How can the sed run if $searchString is not found?