开发者

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

开发者 https://www.devze.com 2023-03-18 18:56 出处:网络
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开发者_Python百科:

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开发者_Python百科:

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'


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

This was what I needed.


The simplest way to append data is with file redirection.

echo $APPEND >>test.txt


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
}


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


Add a semicolon after the sed substitution command!

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号