Issue
I have my HTML project with following structure:
📦My Site
┣ 📂modules
┃ ┣ 📜123.html
┃ ┗ 📜456.html
┣ 📂cart
┃ ┣ 📜index.html
┃ ┗ 📜cart.html
There are tens of folders and thousands of HTML files.
I want to change varying titles to "My New Website" in all files in all subfolders.
Could you please help me to find Mac Terminal SED command to change title tag?
So I want to change every <title>%Different Titles%</title>
to <title>My New Website</title>
Thanks.
Solution
The following command should do what you expect it to do. This first one is for testing to make sure that the output is as expected. The second command is the one that will modify files in place.
find * -type f -name '*.html' | xargs -n 1 sed -E 's/<title>.+<\/title>/<title>My New Website<\/title>/g'
The -type f
parameter to find
restricts the results to files.
Then the results are piped to xargs
. The -n 1
parameter means to construct a separate command with one argument for each file.
The -E
flag on sed
is important. This allows the +
operator to work as expected. The regex is finding any string in the <title>
tag and replacing the whole tag with your desired tag as in your question.
If the above command has output that you expecting, change it to the following to modify the files in place.
find * -type f -name '*.html' | xargs -n 1 sed -E -i '.bak' 's/<title>.+<\/title>/<title>My New Website<\/title>/g'
Here the -i 'bak'
parameter is added to the command. This is a nuance with macOS as you're using. The -i
flag requires that the used specify the string that is to be appended to the old file before the new, edited file is written to the original filename.
Edited: -r
has been changed to -E
because this has the same effect on macOS and makes the command usable on modern GNU and BDS sed
commands as mentioned in the comment below.
Answered By - Utkonos Answer Checked By - David Marino (WPSolving Volunteer)