Replace matched file path with contents of file at the path with sed

sed

I want to write a short deployment script which enters the contents of javascript-files into the single html file. These js files are currently declared as:

  <script src="js/jquery-1.8.2.js"></script>
  <script src="js/jquery.rotate-2.2.js"></script>
  <script src="js/underscore.js"></script>
  <script src="js/backbone.js"></script>
  <script src="js/backbone.dualstorage.js"></script>
  <script src="js/favourites.js"></script>
  <script src="js/menuItem.js"></script>
  <script src="js/companies.js"></script>
  <script src="js/lectures.js"></script>
  <script src="js/banquette.js"></script>
  <script src="js/menu.js"></script>
  <script src="js/application.js"></script>
  <script src="js/main.js"></script>

I got the fallowing sed script which almost does what I want:

sed -r -e '/<script src="(.*)">/r \1' -e '/<script src="(.*)">/d' index.html

The result of running this sed command with the above input is empty string. I'm uncertine what part of \1 is failing. Is it because references don't work outside of s commands?

Running:

sed -r -e 's/<script src="(.*)">/\1/'

Results in:

js/jquery-1.8.2.js</script>
js/jquery.rotate-2.2.js</script>
js/underscore.js</script>
And so on ...

So obviously the regexp matches the right thing.

Is there any way to debug what \1 holds in the first command to perhaps see if the path is incorrect?

Best Answer

It doesn't work that way. As you say, back references don't work outside of s commands.

You could do it with awk or perl with:

perl -pe 's{<script src="(.*?)">}{
  local$/;open F,"<$1";"<script>".<F>}ge'
Related Question