Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash sed按字面意思使用$stringvar进行追加,而不是使用变量的内容_Bash_Sed - Fatal编程技术网

Bash sed按字面意思使用$stringvar进行追加,而不是使用变量的内容

Bash sed按字面意思使用$stringvar进行追加,而不是使用变量的内容,bash,sed,Bash,Sed,我试图让sed在文件中的文本字符串后追加一行,但它使用替换字符串而不是变量的内容 代码: 但是,example.cpp中返回的所有内容都是 //example.cpp #include <iostream> using namespace std; int main() { //junkStringHere ${!junk}" <- this is what is placed in the document. cout << "This is a t

我试图让sed在文件中的文本字符串后追加一行,但它使用替换字符串而不是变量的内容

代码:

但是,example.cpp中返回的所有内容都是

//example.cpp
#include <iostream>

using namespace std;

int main()
{
//junkStringHere
${!junk}" <- this is what is placed in the document.

    cout << "This is a test.";
}
或者在命令中使用它的任何变体。这只是一个示例,我希望$junk字符串出现在文件中//junkstringher下面的新行上


如果我在垃圾变量通过sed解析之前回显它,它将返回正确的内容,但是我无法让sed正常工作。感谢您的帮助。

单引号不展开变量,请使用双引号。您需要使用双引号反斜杠,但是:

$ echo XXX junkStringHere XXX | (junk="USER"; sed "/.*junkStringHere.*/a \\
     ${!junk}")
XXX junkStringHere XXX
    choroba

我改为使用gawk来修复它

gawk -i inplace '/junkStringHere/{print;print "'"$junk"'";next}1' "$i"

这不是一个sed问题,而是一个shell问题。Shell不使用单引号展开变量,请使用双引号。Sed对shell变量一无所知。无论我使用的引号或方括号的变体是什么,我都会得到相同的输出。用\\替换双引号会将文件中的输出更改为${!junk}\并且将这两个变量都替换为${!junk},最后再加上一个双引号。请提供一个示例。我清楚地证明了这应该是可能的。我编辑了主要的帖子,以便用复制/粘贴代码更好地解释事情。你为什么要使用!有吗?我在网上找到了不同的变量使用方法\\$垃圾或\\${junk}也不起作用。
$ echo XXX junkStringHere XXX | (junk="USER"; sed "/.*junkStringHere.*/a \\
     ${!junk}")
XXX junkStringHere XXX
    choroba
gawk -i inplace '/junkStringHere/{print;print "'"$junk"'";next}1' "$i"