Feanor
Feanor

Reputation: 3690

Edit html file in the .sh script

I have static html file at 'docs/index.html' with ~ 200 lines of code. I need to add html tags to it in 2 places with .sh script. I know there is command sed to edit files, but can't figure out how it is used.

I need to add

<li><a class="reference" href="#front-end-docs">Front end documentation</a></li>

before the

<li><a class="reference internal" href="#indices-and-tables">

or append my tag to the end of the line number 137

and of course, save the file after that :)

And a similar tag in another place. Can you please give me an example on how to with this specific lines of code to insert?

Thanks

Upvotes: 2

Views: 4972

Answers (1)

Adrian Fr&#252;hwirth
Adrian Fr&#252;hwirth

Reputation: 45626

Let's see if I understand your question correctly:

$ cat testfile
one
two
<li><a class="reference internal" href="#indices-and-tables">
four
five

$ sed '3s|\(.*\)|<li><a class="reference" href="#front-end-docs">Front end documentation</a></li>\1|' testfile
one
two
<li><a class="reference" href="#front-end-docs">Front end documentation</a></li><li><a class="reference internal" href="#indices-and-tables">
four
five

Exchange the 3s with the line number in question, e.g. 137s - this tells sed which line you want the substitution to occur. You wrote add before or append, so I am not sure if you actually meant to append the string or prepend it to the line, so move the \1 to wherever you need it. The above command captures the whole line 3 which you can reference by \1 in your replacement string.

Once it gives the desired output, add the -i switch to sed to overwrite the original file.

Upvotes: 3

Related Questions