我有一個變數說$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>