"sed" Command in Linux:
sed is short for "stream editor" that allows you to filter and modifying text of any file.
Use of "sed" command:
For examples first i'm creating here a file:
#cat > sample.txt
this is a package test file.
this is a script test file.
Press Ctrl+D after you finish entering the text.
Now read the file:
#cat sample.txt
this is a package test file.
this is a script test file.
Now, let's see the uses of "sed" command:
1. Replacing or substituting string:
"Sed" command is mostly used to replace the text in a file (sample.txt). The below simple "sed" command replaces the word "file" with "directory" in the file.
#sed 's/file/folder/' sample.txt
this is a package test directory.
this is a script test directory.
Here the "s" specifies the substitution operation. The "/" are delimiters. The "file" is the search pattern and the "directory" is the replacement string.
2. Replacing all the occurrence of the pattern in a line:
The substitute flag /g (global replacement) specifies the "sed" command to replace all the occurrences of the string in the line.
#sed 's/file/directory/g' sample.txt
this is a package test directory.
this is a script test directory.
3. Replacing the nth occurrence of a pattern in a line:
Use the /1, /2, /3 etc flags to replace the first, second, third occurrence of a pattern in a line. The below command replaces the second occurrence of the word "file" with "directory" in a line.
#sed 's/file/directory/2' sample.txt
this is a package test file.
this is a script test directory.
4. Duplicating the replaced line with /p flag:
The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.
#sed 's/file/directory/p' sample.txt
this is a package test directory.
this is a script test directory.
this is a package test directory.
this is a script test directory.
No comments:
Post a Comment