Sed +append number after last matched word in line

sed

I have log file called: log.txt

my target is to add the parameter: $PARAM only after the last string: "Number" in the file log.txt

  • remark: PARAM could be any number

example:

 PARAM=34.43435454

tail -10 log.txt

   date 12.3.2010 Number 2.34
   date 12.3.2010 Number 2.14
   date 12.3.2010 Number 34.43435454

someone have idea how to do that with sed?

Best Answer

After "Number" on every line:

sed "s/.*Number/& $PARAM/" log.txt

After "Number" on the last line:

sed "\$s/.*Number/& $PARAM/" log.txt

After "Number" the last time it appears in the file:

sed "/Number/!b;:a;\$!N;/\n.*Number/{h;s/\n[^\n]*\$//p;g;s/^.*\n//};\$!ba;s/^\(.*Number \)/\1$PARAM/" log.txt

Explanation of the last version:

  • /Number/!b - if the line doesn't contain "Number" branch to the end of the script and print the line
  • :a - loop label "a"
    • \$!N - if it's not the last line of the file, append the next line to the end of the contents of pattern space
    • /\n.*Number/{ - if pattern space includes "Number" after a newline then
      • h - copy pattern space to hold space
      • s/\n[^\n]*\$//p - delete the part after the newline and print the remainder
      • g - copy hold space to pattern space
      • s/^.*\n//} - delete the part before the newline, end if
  • \$!ba - branch to label "a"
  • s/^\(.*Number \)/\1$PARAM/ - add the contents of the variable after "Number"
Related Topic