我有一个变量说$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>