Mediawiki
Help resources
Announcements of releases and security updates
https://lists.wikimedia.org/mailman/listinfo/mediawiki-announce
Cheatsheet
Keyboard shortcut
https://www.mediawiki.org/wiki/VisualEditor/Portal/Keyboard_shortcuts
- Save: Alt+s (non-mac), Ctr+Option+s (Mac)
- Preview: Alt+p (non-mac), Ctrl+Option+p (Mac)
Install mediawiki on ubuntu
http://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_GNU/Linux
Check requirement
php -v mysql -V # capital V
http://localhost/mediawiki setup
- Language
- Welcome to MediaWiki!
- Environmental checks
- Copyright and Terms
- Connect to database - MySQL settings
- Database host: localhost
- Database name: (default is my_wiki)
- Database table prefix: (Leave it empty)
- Database username: root (saved in LocalSettings.php - $wgDBuser, no need to change)
- Database password: (saved in LocalSettings.php - $wgDBpassword)
- Database settings
- Storage engine: InnoDB
- Database character set: Binary
- Name
- Name of wiki: (saved in LocalSettings.php - $wgSitename)
- Administrator account
- Your username: (will be saved in the database)
- Password: (will be saved in the database)
- Email address: (leave it empty)
- Uncheck 'Share data about this installation with MediaWiki developers.'
- Check 'I'm bored already, just install the wiki.'
If we choose 'Ask me more questions', we will get more questions to answer
- Options
- User rights profile: Open wiki/Account creation required/Authorized editors only/Private wiki
- Copyright and license: Creative Commons Attribution/.../No license footer/Select a custom Creative Commons license
- Email settings
- Skins
- Extensions: Gadgets, ImageMap, InputBox, Interwiki, LocalisationUpdate, Nuke, ParserFunctions, PdfHandler, Renameuser, SpamBlacklist, SyntaxHighlight_GeSHi, TitleBlacklist, WikiEditor
- Images and file uploads: Enable file uploads, Logo URL
- Advanced configuration: PHP object caching (APC, APCu, XCache or WinCache)
At the end, we will be notified to download LocalSettings.php file. The new database will be created now.
$ mysql -u root -p -e 'SHOW DATABASES' $ mysql -u root -p -e 'SHOW TABLES' DB_NAME
Enable tex for formula
- http://www.mediawiki.org/wiki/Manual:Enable_TeX
- http://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_GNU/Linux
- http://www.siteground.com/tutorials/mediawiki/mediawiki_math.htm
1. The following line is coming from an earlier bookmarked tutorial (not sure if it is needed anymore)
apt-get install mediawiki-math
2. Download Math extension from this link
3. Then you should extract the archive in the "extensions" folder within your MediaWiki installation directory.
4. Next, you need to add the following line to your LocalSettings.php file:
wfLoadExtension( 'Math' );
sudo apt-get install ocaml cd extensions/Math/math make
6. The next step is to execute the "maintenance/update.php" script via shell:
php maintenance/update.php
Done. Go to test it. [Tested on mediawiki 1.22 on Ubuntu 12.04]. Navigate to "Special:Version" on your wiki to verify that the extension is successfully installed.
Skins
The default skin is vector.
MobileFrontEnd
- https://www.mediawiki.org/wiki/Extension:MobileFrontend to download the extension and extract it to extensions/ folder
- Go to https://www.mediawiki.org/wiki/Skin:Minerva_Neue to download the MinervaNeue skin and extract it to skins/ folder
cd Downloads wget https://extdist.wmflabs.org/dist/extensions/MobileFrontend-REL1_30-5ecc673.tar.gz wget https://extdist.wmflabs.org/dist/skins/MinervaNeue-REL1_30-7ee8663.tar.gz tar xzvf MobileFrontend-REL1_30-5ecc673.tar.gz -C ../mediawiki-1.30.0/extensions/ tar xzvf MinervaNeue-REL1_30-7ee8663.tar.gz -C ../mediawiki-1.30.0/skins
- Use a table or phone to test the effect. It works. The changes I made to <LocalSettings.php>
wfLoadSkin( 'MinervaNeue' ); # put it in the same section of wfLoadSkin wfLoadExtension( 'MobileFrontend' ); $wgMFAutodetectMobileView = true; $wgMFDefaultSkinClass = 'SkinMinerva'; $wgShowExceptionDetails = true; # debugging use only
Install on Ubuntu 16.04, 18.04
I follow this guide to install LAMP.
However the SSH setting will be affected since ufw will assume the default port. So I follow this guide to fix the port problem on OpenSSH.
How to install MediaWiki on Ubuntu 18.04 LTS
Install mediawiki on debian
Link here [1]
Install mediawiki through Vagrant + VirtualBox
https://www.mediawiki.org/wiki/MediaWiki-Vagrant
Several extensions have an instruction for vagrant engine.
vagrant roles enable mobilefrontend --provision
vagrant enable-role multimediaviewer vagrant provision
Run mediawiki with Docker
- https://www.mediawiki.org/wiki/Docker
- Official Docker repository
- There are different choices on https://hub.docker.com/
- https://hub.docker.com/r/simplyintricate/mediawiki/ (10K+ pull & include Dockerfile) & Setup MediaWiki and Postgres with Docker
- https://hub.docker.com/r/bitnami/mediawiki/ (50K+ pull & include Dockerfile) & Bitnami Docker Image for MediaWiki
- https://hub.docker.com/r/appcontainers/mediawiki/ (100K+ pull, include Dockerfile) & How to setup Mediawiki in seconds using Docker?
Install mediawiki on XAMPP
- https://www.mediawiki.org/wiki/Manual:Installing_MediaWiki_on_XAMPP
- https://lifehacker.com/354005/run-your-personal-wikipedia-from-a-usb-stick
LocalSettings.php
- $wgSitename = "BRB-ArrayTools";
The protocol and server name to use in fully-qualified URLs
- $wgServer = "https://YOURDOMAIN.COM";
- $wgSecureLogin = true;
- $wgLogo = "$wgScriptPath/YOURLOGO.png";
- $wgEnableEmail = false;
The base URL path
Database settings
- $wgDBtype = "mysql";
- $wgDBserver = "localhost";
- $wgDBname = "MYWIKIDB";
- $wgDBuser = "root"; # not the wiki user
- $wgDBpassword = "MYPASSWORD"; # not the password used to log in the mediawiki
Shared memory settings
- $wgMainCacheType = CACHE_ACCEL;
To enable image uploads, make sure the 'images' directory is writable, then set this to true:
- $wgEnableUploads = true;
If you use ImageMagick (or any other shell command) on a Linux server, this will need to be set to the name of an available UTF-8 locale
- $wgShellLocale = "en_US.utf8";
Extensions
- wfLoadExtension( 'SyntaxHighlight_GeSHi' );
- $wgFileExtensions = array('txt','svg','png','gif','jpg','jpeg','doc','xls','mpp','pdf','ppt','tiff','bmp','docx', 'xlsx', 'pptx','ps','odt','ods','odp','odg');
- $wgSVGConverter = 'ImageMagick';
- $wgTrustedMediaFormats = array('text/plain');
- $wgDisableCounters = true;
- $wgLocaltimezone = "America/New_York";
- $wgLocalTZoffset = date("Z") / 60;
- date_default_timezone_set( $wgLocaltimezone );
- require_once("$IP/extensions/Math/Math.php");
- $wgFavicon = "$wgScriptPath/favicon32.ico";
Customize
Customize MediaWiki into Your Ultimate Collaborative Web Site
Uninstall mediawiki
- delete the directory containing the wiki's files
- remove the MySQL database holding your wiki
mysql> DROP DATABASE wikidb;
Mediawiki database
MySQL
See the internal MySQL link.
- It seems not necessary to create a new user for storing the mediawiki database; root is OK
- The mediawiki database administrator information will not be saved to the database
- The mediawiki user account will be written to the database.
Users
A list of users including the system administrator can be found under Special pages > User list (No log in is required).
The administrator and users information is saved in the 'user' table of the wiki database. The can be seen by looking at the phpMyAdmin page. LocalSettings.php only saved the database name and username/password in order to get an access.
To reset user's password, follow official wikipedia page
# set the password for username 'example' to 'newpassword' sudo php changePassword.php --user=example --password=newpassword
Format
Preformatted text with text wrap
Search 'Customized preformatted' on the Formatting page.
<pre style="white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* IE 5.5+ */ " > YOUR TEXT </pre>
Color format: CSS
- https://www.mediawiki.org/wiki/Manual:CSS
- https://meta.wikimedia.org/wiki/Wiki_color_formatting_help for a list of common used colors.
Text is red.
<span style="color: red"> Text is red. </span>
Another example: Template::Mvar.
Preformatted text: nowiki
If we want to escape from wikipedia's interpretation & avoiding using pre which will create a block, we can use nowiki. One example is {{mvar}} instead of {{{1}}}.
Display special characters like backslash using unicode
- https://en.wikipedia.org/wiki/Help:Special_characters
- HTML Unicode (UTF-8) Reference, UTF-8 Mathematical Operators. For example to display the symbols ∖[ we can use this trick. The pre and nowiki tags do not work.
- Character Entities Cheat Sheet for HTML, CSS (content) and Javascript. . For example, ► or → represents a right arrow.
Formatting: Superscript and subscript
Use
<sup>1</sup>
or sub keyword.
Syntax highlight
Use the "syntaxhighlight" (for newer versions of mediawiki) or source (for older versions) tag for inline/non-inline syntax highlight. For example,
library(d3Network) Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D") Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I") NetworkData <- data.frame(Source, Target) d3SimpleNetwork(NetworkData, height = 800, width = 1024, file="tmp.html")
can be created by
<source lang="rsplus"> library(d3Network) Source <- c("A", "A", "A", "A", "B", "B", "C", "C", "D") Target <- c("B", "C", "D", "J", "E", "F", "G", "H", "I") NetworkData <- data.frame(Source, Target) d3SimpleNetwork(NetworkData, height = 800, width = 1024, file="tmp.html") </source>
Note for some reason, when I use the syntaxhighlight tag (use syntaxhighlight instead of source tag), 'r' is not recognized on my mediawiki 1.22 although 'bash' works.
This syntax highlight extension package https://github.com/artemklevtsov/MediaWiki-SyntaxHighlight seems more complete. It supports markdown, cpp, r, bash, cxx, ... (no Fortran?) languages. But highlight.js library supports even more.
If we need to use code syntaxhighlight with a list, we shall put the beginning "syntaxhighlight" tag immediately after the paragraph instead of a new line. Putting the tag immediately after the paragraph allows an indentation of the code.
It seems the inline parameter does not work.
Create tables
- http://www.tablesgenerator.com/mediawiki_tables
- https://www.mediawiki.org/wiki/Help:Tables. If the text in the cell should contain a line break, use <br/> instead.
- Tables with alternative row colors; see an example here.
- The following is an example of a table from the main page of UbuntuGuide.org (link were not modified).
Introduction | Installation | Packages and Repositories |
File Managers | ||||
Desktop Add-ons | Virtual Machines | Games and Entertainment |
Internet |
Indent a table or math equation in a list
Use single, double, triple colons. See a discussion and my example here.
Note that if the table is inside a second bullets (**), the bullet level will be reset.
Link an image but not show it up
Add a colon before "File". For example [[:File:myImage.png]] . See
Indent in a numbered list
https://stackoverflow.com/questions/4994174/code-block-in-numbered-list-wiki-syntax
Search "colon" in https://www.mediawiki.org/wiki/Help:Lists.
How can I link to a specific answer?
https://meta.stackexchange.com/questions/45597/how-can-i-link-to-a-specific-answer
Mediawiki/Apache has no response
sudo /etc/init.d/apache2 restart
Auto timeout
php.ini
See
- http://www.mediawiki.org/wiki/Manual_talk:Configuration_settings#Auto-Logout
- https://www.mediawiki.org/wiki/Manual:FAQ#…do_I_get_logged_out_constantly?
- https://superuser.com/questions/204905/mediawiki-increase-session-timeout
On ubuntu, change /etc/php5/apache2/php.ini.
session.cache_expire=180 session.gc_maxlifetime = 1440 session.cookie_lifetime = 1440
After modifying php.ini, you need to restart apache. sudo /etc/init.d/apache2 restart
'keep me logged in' option
Make sure to check this option on the login screen.
- https://www.mediawiki.org/wiki/%22Keep_me_logged_in%22_extended_to_one_year/en
- https://www.mediawiki.org/wiki/Manual:$wgCookieExpiration
- https://www.mediawiki.org/wiki/Manual:$wgExtendedLoginCookieExpiration
- https://www.mediawiki.org/wiki/Help:Logging_in
- https://webmasters.stackexchange.com/questions/79907/how-to-set-the-keep-me-logged-in-box-to-true-in-mediawiki-specialuserlogin
Errors and symptoms
https://www.mediawiki.org/wiki/Manual:Errors_and_symptoms
Sorry! We could not process your edit due to a loss of session data. You might have been logged out. Please verify that you're still logged in and try May be related to Cookies. See also Discussion.
favicon
Move favicon.ico to the mediawiki folder and include the following line in the <LocalSettings.php>
$wgFavicon = "$wgScriptPath/favicon.ico";
Note that the attribute of the ico file has to be at least 644. If not, just run the following line
chmod 644 favicon.ico
To download a favicon, use the approach here. For example, to download the favicon icon from https://wiki.ubuntu.com/ website, we just open the url https://wiki.ubuntu.com/favicon.ico.
The approach works is based on the assumption that the favicon.ico file name is not changed and usually located under the website root directory.
Change skin
- https://www.mediawiki.org/wiki/Manual:Skins
- http://www.inmotionhosting.com/support/edu/mediawiki/change-media-wiki-appearance/changing-mediawiki-skins
- https://www.hostknox.com/tutorials/mediawiki/skins
Change user's password
https://www.mediawiki.org/wiki/Manual:Resetting_passwords
tackle slowness when saving pages
- Maybe it is because packages are automatically updated by OS. Use zgrep -h 'status installed' /var/log/dpkg.log* | sort | tail -n 100 to see updated packages and also Ubuntu -> System restart required. Rebooting the system should help.
- https://www.mediawiki.org/wiki/Manual:Performance_tuning
- https://www.mediawiki.org/wiki/User:Aaron_Schulz/How_to_make_MediaWiki_fast
- Slow MediaWiki: Optimize to Enhance Performance Part 1, Part 2
- Alternative PHP Cache (php-apc)
In summary:
1. Install php-apc. sudo apt-get install php-apc
2. nano LocalSettings.php. Change $wgMainCacheType from CACHE_NONE to CACHE_ACCEL.
$wgMainCacheType = CACHE_ACCEL;
3. (optional) sudo /etc/init.d/apache2 reload
Alternatives to mediawiki
3 Alternatives To MediaWiki When Hosting Your Own Wiki
15 best alternative to MediaWiki?
Article size and its limit
To view what the size of the current (and other revisions) of the page is, open the page on the frontend and view its history.
How to change the maximum allowed page size in MediaWiki
By default the size is 2048 KB. You can modify it in LocalSettings.php.
$wgMaxArticleSize = 100; # 100 KB
Shorten URL (remove index.php)
- https://www.mediawiki.org/wiki/Manual:Running_MediaWiki_on_Debian_or_Ubuntu#Pretty_URLs
- Apache guide. Keywords: RewriteRule & index.php
- Configuring Short URLs in MediaWiki. It provides two ways to shorten the URL. One is to use alias and the other is Rewriting.
- How To Install MediaWiki on Ubuntu 18.04 LTS. Follow Steps 7 & 8.
# Enabling mod_rewrite sudo a2enmod rewrite sudo systemctl restart apache2 # Setting Up Apache2 configuration file sudo nano /etc/apache2/sites-available/mediawiki.conf # new file sudo a2ensite mediawiki.conf sudo a2dissite 000-default.conf sudo apache2ctl configtest sudo systemctl restart apache2 # Setting up the rewrite rules sudo nano /var/www/html/.htaccess # new file # LocalSettings.php sudo mv /var/www/html/mediawiki /var/www/html/w sudo nano /var/www/html/w/LocalSettings.php # $wgScriptPath = "/w"; # $wgArticlePath = "/wiki/$1"; # $wgUsePathInfo = true;
where /etc/apache2/sites-available/mediawiki.conf is
<VirtualHost *:80> <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
and /var/www/html/.htaccess is
# Enable the rewrite engine RewriteEngine On # Short URL for wiki pages RewriteRule ^/?wiki(/.*)?$ %{DOCUMENT_ROOT}/w/index.php [L] # Redirect / to Main Page RewriteRule ^/*$ %{DOCUMENT_ROOT}/w/index.php [L]
- Before: browse http://localhost/mediawiki/index.php/ and no redirect.
- Now: browse http://localhost/ and it will redirect to http://localhost/wiki/.
Change/move main page title
How to change MediaWiki “Main Page” title?
Registration time, password
Preferences > User Profile. From here we can see when the user has registered and there is an opportunity to change the password.
Extensions
Google Analytics
http://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration#Installation
ImageMap
https://www.mediawiki.org/wiki/Extension:ImageMap
Math
MobileFrontEnd
https://www.mediawiki.org/wiki/Extension:MobileFrontend
WikiEditor
https://www.mediawiki.org/wiki/Extension:WikiEditor
The 2nd line is required from my experience
wfLoadExtension( 'WikiEditor' ); $wgDefaultUserOptions['usebetatoolbar'] = 1;
YouTube
https://www.mediawiki.org/wiki/Extension:YouTube
Math extension
- http://www.mediawiki.org/wiki/Extension:Math
- https://www.mediawiki.org/wiki/Extension:Math/advancedSettings. It include info about texvc. texvc takes formulae and produces formatted output in HTML, MathML, and PNG images.
Mathoid server
Note that if I open a math equation in a new tab, it will show the link to en.wikipedia.org (e.g. C-statistic) created in my Survival data page. If I host mediawiki on Rasp Pi3, a mediawiki page with lots of math symbols will be too slow to be loaded.
However, Ubuntu does not have a support on Mathoid which can convert math to SVG instead of PNG.
I can only get PNG rendering for Math formula on Ubuntu. However if I use Mediawiki Docker image which based on PHP and PHP is based on Debian, I can get SVG images for Math formula.
If I go to Preferences > Appearance, the Math mode is "MathML with SVG or PNG fallback" in Docker but "PNG images" in Ubuntu. If I try to change to "MathML with SVG or PNG fallback" in Ubuntu, it will break.
Installing the MediaWiki Math extension is easier now (with a short instruction) March 2018.
Mathoid server on Ubuntu
See MathEasy extension.
Mathoid on Docker
https://github.com/nlpub/mathoid-docker
SimpleMathJax
Another way to get the SVG instead of PNG format for mathematical formulae is to use the SimpleMathJax extension (see a discussion). The instruction needs to be modified.
- After unzip the zip file to the extensions folder it is necessary to change the folder name from 'SimpleMathJax-master' to 'SimpleMathJax' (if we did not do that, the maintenance/update.php will issue errors)
- The renaming step is not necessary if we use the 'git' command to download the files; i.e. git clone https://github.com/jmnote/SimpleMathJax.git
It works when I tested on Ubuntu 18 + Mediawiki 1.31 + SimpleMathJax 0.7.3.
root@ubuntu1804:/var/www/html/mediawiki/extensions# ls -lh SimpleMathJax/ total 20K -rw-r--r-- 1 root root 829 May 12 11:47 extension.json drwxr-xr-x 3 root root 4.0K May 12 11:47 modules -rw-r--r-- 1 root root 1.7K May 12 11:47 README.md -rw-r--r-- 1 root root 1.3K May 12 11:47 SimpleMathJax_body.php -rw-r--r-- 1 root root 391 May 12 11:47 SimpleMathJax.php
How to display index under the sigma sign
Template
https://www.mediawiki.org/wiki/Help:Templates
Template:Mvar
<span class="texhtml mvar" style="font-style:italic;">{{{1}}}</span>
- Example: https://en.wikipedia.org/wiki/Partial_least_squares_regression. In my personal mediawiki page, I need to create a new page called Template:Mvar with the same content as in mediawiki. Then my mediawiki will understand {{mvar}}. Note: the font I got still different from what I see on wikipedia; maybe I miss that one.
- How to import Wikipedia Templates into your own MediaWiki
Trouble shooting
Import images
- dumpUploads.php
- importImages.php
$ php maintenance/dumpUploads.php | grep Boxplot images/2/25/Boxplot.svg $ find images -iname *Boxplot* images/thumb/2/25/Boxplot.svg images/thumb/2/25/Boxplot.svg/120px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/180px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/450px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/600px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/1200px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/400px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/240px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/900px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/300px-Boxplot.svg.png images/thumb/2/25/Boxplot.svg/200px-Boxplot.svg.png
# Get a list of uploaded images, save them to a new folder php maintenance/dumpUploads.php | grep images | xargs tar czvf ~/Downloads/backup_files.tar.gz mkdir ~/Downloads/imagesdir tar xzvf backup_files.tar.gz -C ~/Downloads/imagesdir cd ~/Downloads/imagesdir find images -type f -exec cp {} . \; rm *.txt rm *.pdf rm -rf images # scp imagesdir to my local computer. Then run php maintenance/importImages.php --overwrite /mnt # where imagesdir has been mounted to /mnt # For some reason, some images are not imported? chown -R www-data:www-data images
Fatal exception of type "Wikimedia\Rdbms\DBQueryError"
Run php update.php.
Backup for offline
https://webmasters.stackexchange.com/questions/28702/how-to-dump-a-mediawiki-for-offline-use
wget -k -p -r -R '*Special*' -R '*Help*' -E http://example.com/wiki
Mediawiki to Markdown
https://github.com/philipashlock/mediawiki-to-markdown
How to Create Your Own Offline Wiki
https://www.wikihow.com/Create-Your-Own-Offline-Wiki
Comparison of wiki hosting services
https://en.wikipedia.org/wiki/Comparison_of_wiki_hosting_services
Use Github Wiki
- https://help.github.com/articles/about-wikis/
- Lightweight markup comparison
- By different edit mode (AsciiDoc, Creole, Markdown, MediaWiki, Org-mode, Pod, RDoc, Textile and reStructuredText):
- reStructuredText based. Table of contents can be automatically generated.
- Mediawiki based. Table of contents can be inserted by adding "__TOC" at the desired position. However, the external image cannot be resized; see In MediaWiki, is there a way I can resize to external images?. Note the image looks large in Preview. It seems he displayed image size will be automatically adjusted.
- Markdown (*.md files. Editor toolbar will be enabled): It is easy to change image size; see another way on matrixstats' Wiki. How do I create some kind of table of content in GitHub wiki?. It seems this can only be painfully created by using the anchor-link method. Google: Table of Contents Markdown Generator. For Atom editor, check out this Markdown TOC package.
- Places to share images: imgur
- How to download all images from your account
Clean up
I use a small R script to clean up the header levels. Normally the header should start with one "=".
x <- readLines("~/Downloads/linux.txt") # Manual check possible header levels # The original source (eg Ubuntu) may be messed up # Most are starting with '===' but two are starting from '==' # In that case, we need to fix the source first # This solves the mystery that TOC does not show up in mobile device cnt <- 0 ind <- grep("^== ", x) if (length(ind) > 1) { cat("Number of ==", length(ind), "\n") cnt <- cnt + 1L x[ind] <- gsub("==", paste0(rep("=", cnt), collapse = ""), x[ind]) } # The rule may fail if '===' occurs in a preformated text/code # In this case we can safely ignore the cases. ind <- grep("^=== ", x) if (length(ind) > 1) { cat("Number of ===", length(ind), "\n") cnt <- cnt + 1L x[ind] <- gsub("===", paste0(rep("=", cnt), collapse = ""), x[ind]) } ind <- grep("^==== ", x) if (length(ind) > 1) { cat("Number of ====", length(ind), "\n") cnt <- cnt + 1L x[ind] <- gsub("====", paste0(rep("=", cnt), collapse = ""), x[ind]) } ind <- grep("^===== ", x) if (length(ind) > 1) { cat("Number of =====", length(ind), "\n") cnt <- cnt + 1L x[ind] <- gsub("=====", paste0(rep("=", cnt), collapse = ""), x[ind]) } writeLines(x, "~/Downloads/linux2.txt")