Linux sed command usage example

 Sed is an important text processing tool on Linux, which can replace, delete, add, select specific lines and other functions of file content. The following is an introduction to the use of the sed command through common sed examples.

print file content

(1) Print the specified line

sed -n '1p' /etc/passwd # print line 1
sed -n '10p' /etc/passwd # print line 10
sed -n ' $p' /etc/passwd # print the last line

(2) Print the pattern matching line

sed -n '/root/p' /etc/passwd # print the line containing the root string
sed -n ' /r.*p/p' /etc/passwd # print lines matching the regular expression r.*p

(3) Print the contents of the specified range

sed -n '1,3p' /etc/passwd #Print lines 1-3
sed -n ' 3,/root/p' /etc/passwd #Print line 1 to the first line that matches the root string
sed -n ' /root/,/oracle/p' /etc/passwd #Print the line matching the root string to the oracle string
sed -n ' 1,$p' /etc/passwd #Print the full text

Modify file content

insert

sed '3i new line' /etc/passwd #Insert a line with new line before line 3
sed '3a new line' /etc/passwd #Insert a line with new line after line 3
sed '3c new line' /etc/passwd #Replace line 3 with the line with the content of new line
sed ' 1,3c new line' /etc/passwd #Replace lines 1-3 with lines with new line content

delete

sed '1d' /etc/passwd #delete line 1
sed ' 1,3d' # delete lines 1-3
sed ' $d' # delete the last line
sed ' /root/d' /etc/passwd #delete the line containing root
sed ' 3,/root/p' /etc/passwd #delete line 1 to the first line that matches the root string
sed ' /root/,/oracle/d' /etc/passwd #Delete the line matching the root string to the oracle string

replace

sed 's/root/ROOT/g' /etc/passwd #Full text lowercase root is replaced by uppercase root
sed ' 1,5s/root/ROOT/g' /etc/passwd #Replace lowercase root on lines 1-5 with uppercase root
sed ' /root/,/oracle/ s/root/ROOT/g' #Replace the lowercase root between the lines containing the root string to the oracle string with uppercase ROOT
sed 's /\$//g' /etc/passwd # delete the $ character
sed -n 's /root/hello &/p' /etc/passwd #Replace root with hello root. & means match the result of the previous pattern

print line number

sed -n '/root/=' /etc/passwd # print the line number containing the root string

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325288996&siteId=291194637