
変数sayがあり、$strToInsert
ファイルがありますfile.html
。最後の項目を見つけて、</head>
それを含む行の前に新しい行を挿入して$strToInsert
内容を埋める方法を知りたいです。
これが私が持っているものです:
GACODE="UA-00000000-1"
if [ "$2" = "" ]
then
echo "Usage: $0 <url to extract doxygen generated docs into> <GA tracker code if needed>"
echo "Using default"
else
GACODE = $2
fi
GASTR="<script>var _gaq = _gaq || [];_gaq.push([\'_setAccount\', \'$GACODE\']);_gaq.push([\'_trackPageview\']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript\'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();</script>"
しかし、私が試したとき:
sed -i 's#</head>#'$GASTR'\n</head>#' header.html
私は得る:
sed: -e expression #1, char 21: unterminated `s' command
私のコードに問題がありますか?
答え1
sed -i "s#</head>#$strToInsert\n</head>#" file.html
</head>
しかし、「最後に見たもの」がファイルに複数あることができるという意味かはわかりません。
答え2
sed "/<\/head>/i\
$strToInsert" file.html
以前に新しい行が挿入されます。すべて </head>
、ところでなぜ二つ以上ですか?
答え3
cat "$file" #(before)
1
2 </head>
3
4 </head>
5
6 </head>
strToInsert="hello world"
lnum=($(sed -n '/<\/head>/=' "$file")) # make array of line numbers
((lnum>0)) && sed -i "${lnum[$((${#lnum[@]}-1))]}i \
$strToInsert" "$file"
cat "$file" #(after)
1
2 </head>
3
4 </head>
5
hello world
6 </head>