I need to identify the exact text of San Antonio Generator Running in the output my script which lands to a text file. Once SED finds the specific text, I need it to insert one line above the matched text.
Here is what I have so far that isn't working all that well for me. Any help would be much appreciated.
sed -i '/"\<San Antonio Generators Running\>/i \\' outagereport.txt
Well, you are not searching the pattern that you cite in your text; there's an extra " and an extra s in the pattern. And, try \n for the replacement string.
I'm not a sed expert at all, but it would seem that you need to substitute your string with new-line and then your string. I think you are adding literally nothing with your code above.
Could you try something like this? (no promises at all):-
sed 's/"\<San Antonio Generators Running\>"/^J"\<San Antonio Generators Running\>"/' outagereport.txt
The ^J is a single character generated by pressing Ctrl+v then Ctrl+j
Okay so I tried most of these and the following worked best for me:
sed '/\<San Antonio Generators Running\>/ i\\' outagereport.txt
This is what the output looked like prior to the SED command:
HOSTNAME USERNAME> cat outagereport.txt
San Antonio Generators Running
San Antonio Generator Alarms: Zero
San Antonio Battery Discharge
San Antonio Battery Discharge Zero
San Antonio Comm Power Fail
San Antonio Comm Power Fail Zero
San Antonio Isolated Sites
San Antonio Isolated Sites Zero
This is the result with the SED command:
HOSTNAME USERNAME> sed '/\<San Antonio Generators Running\>/ i\\' outagereport.txt
San Antonio Generators Running
San Antonio Generator Alarms: Zero
San Antonio Battery Discharge
San Antonio Battery Discharge Zero
San Antonio Comm Power Fail
San Antonio Comm Power Fail Zero
San Antonio Isolated Sites
San Antonio Isolated Sites Zero
Since some three of these strings have the same sequence, such as isolated sites and isolated sites Zero, how can I add a line above only the first instance?
sed does not have variables; in order to avoid the match in the further lines one must read them in a loop.
In traditional multi-line syntax (not possible in csh/tcsh):
sed '
/\<San Antonio Generators Running\>/ {
i\
:L
N
$!bL
}
' outagereport.txt
Wouldn't it be simpler to just match entire lines? Using a BSD based sed on Mac OS X with your sample input file:
$ sed '/^San Antonio Battery Discharge$/i\
\
/^San Antonio Comm Power Fail$/i\
\
/^San Antonio Generators Running$/i\
\
/^San Antonio Isolated Sites$/i\
\
' outagereport.txt
San Antonio Generators Running
San Antonio Generator Alarms: Zero
San Antonio Battery Discharge
San Antonio Battery Discharge Zero
San Antonio Comm Power Fail
San Antonio Comm Power Fail Zero
San Antonio Isolated Sites
San Antonio Isolated Sites Zero
$