bash 如何通过命令行将变量文本附加到文件的最后一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6625148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:44:30  来源:igfitidea点击:

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

bashsed

提问by Martin Thoma

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

你能告诉我我(一个 Linux 用户)如何将文本添加到文本文件的最后一行吗?

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.

它有效,但 $APPEND 被添加到变量的内容中。我知道这样做的原因是我用于 sed 的单引号 (')。但是当我简单地将 ' 替换为 " 时,文件中不会添加任何文本。

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.

你知道解决这个问题的方法吗?我不坚持使用sed,它只是我想到的第一个命令行工具。您可以使用您喜欢的每个标准命令行程序。

edit: I've just tried this:

编辑:我刚刚试过这个:

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

回答by Martin Thoma

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

This was what I needed.

这正是我所需要的。

回答by SingleNegationElimination

The simplest way to append data is with file redirection.

追加数据的最简单方法是使用文件重定向。

echo $APPEND >>test.txt

回答by Fredrik Pihl

Using this as input:

使用它作为输入:

1 a line
2 another line
3 one more

and this bash-script:

和这个 bash 脚本:

#!/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:

使用awk的解决方法:

BEGIN {s="42 is the answer"}

{lines[NR]=
sed '${s/$/'"$APPEND"'/}' test.txt
} END { for (i = 1; i < NR; i++) print lines[i] print lines[NR], s }

回答by ToonZ

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

回答by Hyman

Add a semicolon after the sed substitution command!

在 sed 替换命令后添加分号!

##代码##