As a Linux user, it’s important to know how to modify text files through the command line. One common scenario is changing a single line in a text file, such as enabling or disabling a feature. But what if the OS doesn’t have any text editor installed at all?
In this tutorial, we’ll cover how to find and replace a line in a text file without using a text editor, and we’ll use the example of enabling allow_url_include
in the php.ini
configuration file.
Locate the Text File
The first step is to locate the text file that you want to modify. In this example, we’ll use the php.ini
which is a text file located in the /etc/php/7.0/cli
directory.
Check the Current Value
Before making any changes, it’s important to check the current value of the setting that you want to modify. In this example, we want to enable allow_url_include
, which should be set to Off
by default. To check the current value, we can use the following command:
grep "allow_url_include" /etc/php/7.0/cli/php.ini
This should output a line that shows the current value of allow_url_include
.
Modify the Configuration File
To modify the configuration file, we can use the sed
command. The sed
command is a powerful stream editor that can perform text transformations on an input stream (a file or input from a pipe). In this example, we’ll use sed
to replace allow_url_include = Off
with allow_url_include = On
.
Here’s the command to make the change (since my file is in root directory then I need sudo
):
sudo sed -i 's/allow_url_include = Off/allow_url_include = On/g' /etc/php/7.0/cli/php.ini
This command will search for the string allow_url_include = Off
and replace it with allow_url_include = On
in the php.ini
file.
The -i
option tells sed
to modify the file in place, and the g
at the end of the command tells sed
to replace all occurrences of the string, not just the first one.
Verify the Change
To verify that the change was made successfully, we can run the same grep
command previously:
grep "allow_url_include" /etc/php/7.0/cli/php.ini
This should output a line that shows the new value of allow_url_include
.
Conclusion
In this tutorial, we learned how to modify a configuration file in Linux without using a text editor. We used the sed
command to find and replace a line in the php.ini
configuration file, but you can use this technique to modify any configuration file on your system. You should always back up any files that you modify. 🙂