Need assistance with appending strings using sed and variables

HI,

Can't seem to find anything on the forums to fix this.

I have a file, one line within this will not have a specific string at the end.

I have the string, but need to append it to the specific line which has it missing.

I need to use a variable for this, $string - I am using double quotes as below:

sed "/!*missing_string/a\ $string" file

Any help would be much appreciated.

Many thanks

whats the problem??

sed '/missing_string/!s/$/ missing_string/g' file

I've added a space in front of the second "missing_string" - assuming that you want a space before the word is appended to the line.

sed "s/missing_string.*/& $string/" file

Regards

hmm... I missed the $string part - sorry about that.
My script only works on the commandline - with the string manually provided

Thanks guys for your replies, but unfortunately it's still not writing the string to the end of the file.

It gets past the parser, and the rest of the script executes without problem, but no string on the end of my incomplete line.

Perhaps I didn't do a good job of explaining the problem:

1) My file has x amount of lines
2) One of these lines will have a string missing from the end of it
3) I have the string that needs to be appended to this line, stored as a variable $string
4) I want sed to locate the line with a missing end, the end is in format *T00:00:00
5) If it finds a line that doesn't have an ending matching *T00:00:00, it needs to append $string to this line.

Any further help will be greatly appreciated.

many thanks

What is your script written in?

bash shell script

If awk is allowed:

awk -v s=$string '!/T00:00:00$/{$(NF+1)=s}1' file > newfile

Regards

Thanks Franklin

Nearly there, but $string is being written one-space into the beginning of the line, not at the end.

Trying to work it out but haven't cracked it yet!

It works fine for me, can you post some lines of your file including a line without the specific string at the end?

Nearly there:

awk -F"|" -v s=$string '!/T00:00:00/{$NF=s}1' file > newfile

(Forgot to mention that each line in the file has | as the field delimiter).

This line is writing $string to the end of the line, but replacing all my | delimiters with spaces! :mad:

Any ideas why it is doing this?

much appreciated

Try this:

awk -v s=$string 'BEGIN{FS=OFS="|"}!/T00:00:00$/{$(NF+1)=s}1' file > newfile

With $(NF+1)=s I add a new field at the end of the line but with $NF=s you're replacing the last field with your string.

Regards

That's done it!

 
awk -v s=$string 'BEGIN{FS=OFS="|"}!/T00:00:00/{$NF=s}1'

Perfect, thank you Franklin! :b:

(It seems to work fine replacing the last field, I believe the field is there but just empty).