I am trying to add a string called "SPEC1" to the end of a line which starts with BEGIN, but only if that string doesn't already exist. Some of the matched lines may or may not already have the string.
My example file looks like this:
BEGIN value1 value2 value3 SPEC1
some_other_line1
BEGIN value1 value2 value3 value4
some_other_line2
BEGIN value1 value2
And the result should look like this:
BEGIN value1 value2 value3 SPEC1
some_other_line1
BEGIN value1 value2 value3 value4 SPEC1
some_other_line2
BEGIN value1 value2 SPEC1
I am using sed to try and achieve this. My current sed solution is like this:
sed '/BEGIN/ {
s/ \+SPEC1//g
s|\(.*\)|\1 SPEC1|
}' file
Explanation of above:
- Search for lines that start with "BEGIN"
- Look for existing string "SPEC1" (may also have one or more spaces in front) and delete it globally to clean up the file
- Capture the whole matched line (sed BRE style) and append line with "SPEC1"
Is there a better way to achieve this either with sed, awk, perl or bash?
Thanks.