我正在尝试让sed在文件中的一串文本之后追加一行,但是它使用替换字符串而不是变量的内容。
代码:
#!/bin/bash
for i in *.cpp; do
echo "Checking file $i"
if grep -Fxq "//junkStringHere" "$i"
then
junk=$(< /dev/urandom tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
echo $junk
sed -i '/.*//junkStringHere.*/a \\${!junk}' "$i"
else
echo "Nothing to do."
fi
done
我已经尝试了所有迭代的$ junk我能想到/在线阅读。
$junk "$junk" \\$junk" '$junk' ${!junk} ${junk} etc...
但是,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字符串出现在文件中“// junkStringHere”下面的新行上。
如果我在通过sed解析之前回显垃圾变量,它会返回正确的内容但是我无法正常工作。感谢任何帮助。谢谢。
答案 0 :(得分:1)
单引号不扩展变量,使用双引号。但是你需要用双引号反斜杠反斜杠:
$ echo XXX junkStringHere XXX | (junk="USER"; sed "/.*junkStringHere.*/a \\
${!junk}")
XXX junkStringHere XXX
choroba
答案 1 :(得分:-2)
我&#34;&#34;已修复&#34;&#34;它通过使用gawk代替。
gawk -i inplace '/junkStringHere/{print;print "'"$junk"'";next}1' "$i"