I have a file that sometimes has one occurrence or multiple occurrences of the same string. I am needing to search for one or more occurrences in the file and go to the next line and keep the values in that line but add a value to the end yet keeping the rest of the file intact. Here is what I have:

Line: 3, 0, "General Thunderstorm Risk"
 37.74, -87.17
 36.22, -85.50
 34.80, -85.41
 34.01, -85.72
 33.14, -86.64
 32.45, -88.05
 31.88, -89.68
 31.38, -91.39

Line: 3, 0, "General Thunderstorm Risk"
 29.04, -94.27
 29.74, -95.99
 30.91, -98.31
 31.68, -99.14
 32.45, -98.94
 33.58, -97.73
 35.11, -96.96
 36.63, -96.57

if grep "General Thunderstorm Risk" d1.txt; then
echo "General Thunderstorm Risk Detected"
POLYGON=`cat d1.txt | awk '/Line: 4, 0, \"General Thunderstorm Risk\"/{getline; print}'`
cat d1.txt | sed -e 's/Line: 4, 0, \"General Thunderstorm Risk\"/Polygon:/g' | sed -e "s/$POLYGON/$POLYGON, 0, 176, 80, 40/g" > day1
  • grep, awk, sed, cat ... hum! what output do you look for ? – ctac_ Apr 15 at 20:28

To apply something to special lines in sed, you address them, like /pattern/command applies command to lines including the pattern.

If you want to apply a command to the next lines after the pattern line, first advance the line with n command.

Then, to append to the end of the line, use s/$/whatever you want to append/ (the $ stands for the line ending).

Now you need to combine those commands with {}, so the addressing is valid for both of them, and you and up with

sed '/General Thunderstorm Risk/{n;s/$/, 42/;}' yourfile.txt > out.txt

to append , 42 to the line after the match. If that is not what you are looking for, please edit your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.