Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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



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?

share|improve this question
I really don't understand what you want to do. Could you please post an example of the log file before your supposed edit? Also, where does the different numbers come from and how do you want to decide which numbers goes where? Or do you simply want to edit the last line, appending the number (i.e. 34.4343...)? – Sven Jan 26 '11 at 13:22
the target was to add $PARAM value after the last "Number" word in the file , if for example I have 23 Number words then need to append the $PARAM after "Number" word – klod Jan 27 '11 at 9:30
up vote 3 down vote accepted

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"
share|improve this answer
hi little problem the sed actually add the $PARAM number but also delete the word "Number" from the file , how to fix that? – klod Jan 27 '11 at 9:28
@klod: Please see my edited answer. I moved the \\) and a space plus fixed a couple of typos. – Dennis Williamson Jan 27 '11 at 10:06

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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