Sunday, October 30, 2022

[SOLVED] Append some text to the end of multiple files in Linux

Issue

How can I append the following code to the end of numerous php files in a directory and its sub directory:

</div>
<div id="preloader" style="display:none;position: absolute;top: 90px;margin-left: 265px;">
<img src="ajax-loader.gif"/>
</div>

I have tried with:

echo "my text" >> *.php

But the terminal displays the error:

bash : *.php: ambiguous redirect

Solution

You don't specify the shell, you could try the foreach command. Under tcsh (and I'm sure a very similar version is available for bash) you can say something like interactively:

foreach i (*.php)
foreach> echo "my text" >> $i
foreach> end

$i will take on the name of each file each time through the loop.

As always, when doing operations on a large number of files, it's probably a good idea to test them in a small directory with sample files to make sure it works as expected.

Oops .. bash in error message (I'll tag your question with it). The equivalent loop would be

for i in *.php
do 
   echo "my text" >> $i
done

If you want to cover multiple directories below the one where you are you can specify

*/*.php

rather than *.php



Answered By - Levon
Answer Checked By - David Marino (WPSolving Volunteer)