Martin Thoma
Martin Thoma

Reputation: 136277

How can I append a variable text to last line of file via command line?

could you please tell me how I (a Linux-User) can add text to the last line of a text-file?

I have this so far:

APPEND='Some/Path which is/variable'
sed '${s/$/$APPEND/}' test.txt

It works, but $APPEND is added insted of the content of the variable. I know the reason for this is the singe quote (') I used for sed. But when I simply replace ' by ", no text gets added to the file.

Do you know a solution for this? I don't insist on using sed, it's only the first command line tool that came in my mind. You may use every standard command line program you like.

edit: I've just tried this:

$ sed '${s/$/'"$APPEND/}" test.txt
sed: -e Ausdruck #1, Zeichen 11: Unbekannte Option für `s'

Upvotes: 13

Views: 51207

Answers (5)

ToonZ
ToonZ

Reputation: 135

sed '${s/$/'"$APPEND"'/}' test.txt

Upvotes: 3

jack
jack

Reputation: 11

Add a semicolon after the sed substitution command!

(
set -xv
APPEND=" word"
echo '
1
2
3' |
sed '${s/$/'"${APPEND}"'/;}'
#sed "\${s/$/${APPEND}/;}"
)

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

Using this as input:

1 a line
2 another line
3 one more

and this bash-script:

#!/bin/bash

APPEND='42 is the answer'

sed "s|$|${APPEND}|" input

outputs:

1 a line42 is the answer
2 another line42 is the answer
3 one more42 is the answer

Solution using awk:

BEGIN {s="42 is the answer"}

{lines[NR]=$0 }

END {
    for (i = 1; i < NR; i++)
        print lines[i]
    print lines[NR], s
}

Upvotes: 7

Martin Thoma
Martin Thoma

Reputation: 136277

echo "$(cat $FILE)$APPEND" > $FILE

This was what I needed.

Upvotes: 26

SingleNegationElimination
SingleNegationElimination

Reputation: 156148

The simplest way to append data is with file redirection.

echo $APPEND >>test.txt

Upvotes: 8

Related Questions