Issue
I have a bunch of HTML files as shown below:
ati.4.html
fbdevhw.4.html
isdn.ctrl.4.html
modul.efile.4.html
ran.dom.4m.html
tw.policy.4p.html
I need to take the name of the HTML file and prepend it to the first line of each file, such that the lines should be:
<h1>ati(4) - some text tp append</h1>
<h1>fbdevhw(4) - some text tp append</h1>
<h1>isdn.ctrl(4) - some text tp append</h1>
<h1>modul.efile(4) - some text tp append</h1>
<h1>ran.dom(4m) - some text tp append</h1>
<h1>tw.policy(4p) - some text tp append</h1>
Here is what I have done till now. I am close but I think there is a better way to do it in single sed command.
for filename in `ls`
do
rep_text=`echo $filename | sed 's/\.html/\) - some text tp append<\/h1>/' | sed 's/^/<h1>/'
sed -i "1 i\${rep_text}" $filename
done
Output lines which I am getting for prepending:
<h1>ati.4) - some text tp append</h1>
<h1>fbdevhw.4) - some text tp append</h1>
<h1>isdn.ctrl.4) - some text tp append</h1>
<h1>modul.efile.4) - some text tp append</h1>
<h1>ran.dom.4m) - some text tp append</h1>
<h1>tw.policy.4p) - some text tp append</h1>
Not able to convert the 2nd last dot(.) into the round bracket as there can be multiple dots in the file name and I need to only replace the 2nd last dot with ( .
Solution
You may use this script:
for f in *.html; do
IFS=. read -ra a <<< "$f" # split into array using . as delimiter
n=$((${#a[@]} - 2)) # set n=length(array) - 2
sed -i "1 i\<h1>${a[0]}(${a[$n]}) - some text to append</h1>" "$f"
done
Answered By - anubhava Answer Checked By - Willingham (WPSolving Volunteer)