Thursday

Text manipulation: Find and replace Linux commands


Text manipulation is a key aspect of working with text data in various fields such as data science, data engineering, web development, and system administration. There are many tools and techniques available for text manipulation in Linux or Unix-based systems. Some popular tools for text manipulation include:

grep

grep is a command-line utility that searches for patterns in files and directories. It is a powerful tool for finding text in files and can be used with regular expressions for more advanced searches.

- Find all occurrences of the word in a file. 
- Use the grep command in combination with other command to filter the output of those commands

Ex 1: We have a demo.txt file

quoc ~  $ cat demo.txt
This is the first line
UPPER TEXT
And this is the last line

Find all line contains last in demo.txt

quoc ~  $ grep "last" demo.txt
And this is the last line

Ex 2: list all files/directories in a directory that contain the word Document

quoc ~  $ ls | grep Document
Document
Documents

sed

sed is a stream editor that is used to perform text transformations on a file or stream of data. It can be used to replace text, delete lines, and perform other operations on text.

Let's say you have a file called example.txt that contains the following text:

This is an example file.
It contains some text that we want to modify.
We can use the sed command to do this.

And you want to replace all occurrences of the word example with the word sample in this file. You can use the following command:

sed 's/example/sample/g' example.txt

This will search for all occurrences of the word example in the file example.txt and replace them with the word sample. The s stands for substitute, and the g at the end stands for global, meaning that all occurrences of the word example in each line will be replaced, not just the first occurrence.

You can also use the -i flag to perform the substitution directly in the file, without creating a new file:

sed -i 's/example/sample/g' example.txt

0 comments:

Post a Comment