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}/;}"
)
精彩评论