There are times in Linux when you want to find a specific file and change its content. For instance, if you want to find the text "vue" in the language.json file and replace it with "nuxt", how should you do it?
@ language.txt{
"framework": "vue"
}
// We aim to change the "vue" text as follows:
{
"framework": "nuxt"
}
Several methods exist to change the content of a file. Below,
we will try to replace specific text with another text in Linux using the
sed command. We will also explore the use of
regular expressions.
# Changing File Content in Linux with sed
sed helps to find a particular phrase in a file and change it. Its basic syntax is as follows:
sed option 's/targetText/replaceText/' targetFile
After sed, there's an option, and next, you can enter text separated by the / symbol. Each keyword is used as follows:
option //
[Optional] Used when setting optionss //
Finds and replaces texttargetText //
The text to targetreplaceText //
The text that will replace the targettargetFile //
The name of the target fileNow, let's explore how to use it with a simple example.
! Examples of changing text with sed
We will create several examples and look at each case, including the standard case and the one using regular expressions.
Replacing "apple" with "orange"To replace "apple" with "orange" in the file.txt:
sed 's/apple/orange/' file.txt
This is the simplest method.
Replacing all instances of "apple" with "orange"The example above changes only one instance of the text. To change all instances, add a 'g' after the text to be replaced.
sed 's/apple/orange/g' file.txt
Now, all "apple" are changed to "orange".
Using the -i flag option for file modificationWithout using the -i, the file is not saved but only printed. To actually change and save the file, use the -i flag.
sed -i 's/apple/orange/g' file.txt
Changes are displayed, and you can see that the file is modified.
Using regular expressions to replace either "apple" or "banana" with "orange"Regular expressions are basically used, but to apply all recent regular expressions, the -E option is necessary. For example, to use symbols like '+' or '|', you need to add the -E option as follows:
sed -E 's/apple|banana/orange/g' file.txt
Now, using the pipeline symbol, it's possible to find and replace either "apple" or "banana".
We've briefly looked at ways to change file content and text in Linux.