1

In Short

Is there some way to bash command line: echo "***some code***" >> "***all files of some type***" right after the line in the files that includes a certain string such as <body?

In Long

I have to add google analytics to a site. Its got an archive of stuff that goes by a few years.

For some recent archived years I just added :

...
</head>
<body<?php if ($onpageload != "") { echo " onload=\"$onpageload\""; }?>>
<?php include_once("analyticstracking.php") ?>
...

into the common_header.php file

For some of the early stuff they didn't make a common_header.php file. So, for the folders that manage years that don't have common headers there are alot of html files that need this line:

<?php include_once("analyticstracking.php") ?>

Is there some way to bash command line: echo "<?php include_once("analyticstracking.php") ?>" >> "*.html" right after the in the file that includes a certain string such as <body

The site is managed with php, python, and html (with some javascript css etc).

I am on ubuntu. Also note I am newer to this kind of webpage so if my question is somehow a wrong or a stupid question, please just let me know.

Rorschach
  • 3,684
  • 7
  • 33
  • 77

2 Answers2

6

If you, for example, want to add a line before the line containing </body>, editing all files in place, you can

sed -i -e '\@</body>@i\New stuff' *.html

The same, but after the line matching <!-- insert here -->

sed -i -e '/<!-- insert here -->/a\New stuff' *.html

It is rather cumbersome to span multiple lines in sed with an s command. The line-oriented commands are i\ (insert before) and a\ (insert after).

Your particular case would be

sed -i -e '/<body/a\<?php include_once("analyticstracking.php") ?>' *.html

but only if your body tag does not have attributes spanning multiple lines. It is always problematic to edit html/xml files with text tools which are not aware of their structure, but it can work if you are sure of the actual text in the files you are editing.

Dario
  • 2,673
  • 20
  • 24
1

If it's bash you're looking for then I'd recommend sed -e 's/<body/<body <blabla>/g' [html FILE]. If the file contents is <body> then output would be <body <blabla>>. You just substitute blabla with php code. syntax is like

sed -e 's/[search]/[replace]/g' [file name]

where -e is 'extended' flag and g I think that stands for 'return after first match' but I'm not sure so you can as well drop it.

And about many files here's how you do it: Change multiple files

Community
  • 1
  • 1
Piotr Kamoda
  • 956
  • 1
  • 9
  • 24
  • Thanks, this is got me much closer, I will accept the answer once I have it working and can comment the complete working line – Rorschach Feb 15 '17 at 08:41