The Power of sed Command in Linux: Replacement Techniques

The replacement function of sed is very powerful and is also the most common use of sed.

By default, sed does not actually modify the file. If you want to write the modified content back to the file, you need to add the -i option.

Command syntax:

sed ‘[address range|pattern range] s#[keyword to be replaced]#[replacement keyword]#[replacement flags]’ [input file]

Command explanation:

1. [address range|pattern range]: Optional. If not specified, sed will perform the replacement on all lines.

2. “s” means to execute the substitute command.

3. The string to be replaced can be a regular expression.

4. The replacement string must be a specific content.

5. Replacement flags: Optional.

– Global flag g

– Numeric flag (1, 2, 3…)

– Print flag p

– Write flag w

– Ignore case flag i

– Execute command flag e

You can combine one or more replacement flags as needed.

Testing textcat > person.txt <<EOF101,Zhangya,CEO102,BanZhang,CTO103,CKman,COO104,Mr.Sheng,UFO105,GuanRu,CXOEOF

Replace CXO with XOThe Power of sed Command in Linux: Replacement TechniquesIf you want to display only the matching lines, you can combine the -n and p options as follows:

sed -n "s#CXO#XO#gp" person.txt 

The Power of sed Command in Linux: Replacement TechniquesTo replace the second occurrence of a with A, use the following syntax:

 sed 's#a#A#2g' person.txt    

To replace e or uppercase E with F, use the -r option for extended regex and i as follows:The Power of sed Command in Linux: Replacement Techniques

Replace Specific Lines

Replace the first line of text with 200,DongLai,CEO

The Power of sed Command in Linux: Replacement Techniques

Group Replacement by Keywords

Replace the positions of CEO and numbers

The Power of sed Command in Linux: Replacement Techniques

 sed -r 's#(.*),(.*),(.*)#\3,\2,\1#g' person.txt  

To remove the middle name, use the following:

 sed -r 's#(.*),.*,(.*)#\1,\2#g' person.txt  

The Power of sed Command in Linux: Replacement TechniquesReplace the first comma with and the second comma with _. For example: 101-DongLai_CEO

sed -r 's#(.*)(,)(.*)(,)(.*)#\1-\3_\5#g'  person.txt 

The Power of sed Command in Linux: Replacement TechniquesSlow down, listen to the birds sing; or brew a pot of fragrant tea in the afternoon, enjoying a moment of tranquility and comfort; or send a greeting to a long-lost friend, conveying a deep longing. These seemingly ordinary little things can bring endless warmth and emotion to our lives.This concludes this episode! Stay tuned for the next one…

Leave a Comment