Johann
Johann

Reputation: 983

SED: How to insert string to the beginning of the last line

How to insert string to the beginning of the last line?

I want to add a time stamp to a text file which contains multiple lines

var1 = `date`

LINE1
LINE2
LINE3
...
(INSERT var1 here) LASTLINE

sed 's/^/test line /g' textfile inserts characters to the beginning of every line but how can I specifically modify the last line only?

Thanks

Going forward: sed '$s/^/sample text /' textfile works, but only when inserting regular strings. If I try

var1 = "sample text"

and use substition, here are the problems I encounter

  1. using single quotes in sed does not expand variables, so sed '$s/^/$var1/' textfile will insert the string $var1 into the beginning of the last line.

  2. To enable variable substitution I tried using double quotes. It works when I specify the exact line number. something like:

    sed "5s/^/$var1/" textfile

But when I try sed "$s/^/$var1" text file, it returns an error:

sed: -e expression #1, char 5: extra characters after command

Can someone help me please?

Upvotes: 1

Views: 8533

Answers (4)

Vivek Soni
Vivek Soni

Reputation: 1

This command would work for you:

sed -i "5s/^/$var1 /" text file

Upvotes: 0

Jotne
Jotne

Reputation: 41456

sedshould be the best tool, but awk can do this too:

awk '{a[++t]=$0} END {for (i=1;i<t;i++) print a[i];print v$0}' v="$var1" file

It will insert value of var1 in front of last line


Another variation

awk 'NR==f {$0=v$0}1' v="$var1" f=$(wc -l file)

PS you do not need to specify file after awk, not sure why. If you do so, it reads it double.

Upvotes: 0

devnull
devnull

Reputation: 123498

But when I try sed "$s/^/$var1" text file, it returns an error: 

It returns an error because the shell attempts to expand $s since you've used double quotes. You need to escape the $ in $s.

sed "\$s/^/$var1/" filename

Upvotes: 1

Guru
Guru

Reputation: 16984

Like this:

sed '$s/^/test line /' textfile

$ indicates last line. Similarly, you can insert into a any specific line by putting the line number in place of $

Upvotes: 5

Related Questions