sed command extended usage operation

Keywords: Operation & Maintenance

Print the content between a line and a line

If the content of the file test.txt is:

ert
fff
**
[abcfd]
123
324
444
[rty]
**
fgfgf

How can we intercept

[abcfd]
123
324
444
[rty]

What about this part?

Operating commands:

  1. Know the contents of the start and end lines
[root@centos01 t1019]# sed -nr '/\[abcfd\]/,/\[rty\]/p' test.txt
[abcfd]
123
324
444
[rty]
  1. Know which line to which line
[root@centos01 t1019]# sed -n '4,8p' test.txt
[abcfd]
123
324
444
[rty]

How sed converts upper and lower case letters

  • In sed, u se _ for capitalization and _ for lowercase

The document reads as follows

[root@centos01 t1019]# cat test.txt 
ert
fff
**
[abcfd]
123
324
444
[rty]
**
fgfgf
Test line.
  1. Convert the first letter of each word from lowercase to uppercase
[root@centos01 t1019]# sed 's/\b[a-z]/\u&/g' test.txt 
Ert
Fff
**
[Abcfd]
123
324
444
[Rty]
**
Fgfgf
Test Line.
  1. Convert all lowercase to uppercase
[root@centos01 t1019]# sed 's/[a-z]/\u&/g' test.txt 
ERT
FFF
**
[ABCFD]
123
324
444
[RTY]
**
FGFGF
TEST LINE.
  1. Convert all capitals to lowercase
[root@centos01 t1019]# sed 's/[A-Z]/\l&/g' test.txt 
ert
fff
**
[abcfd]
123
324
444
[rty]
**
fgfgf
test line.

sed adds a number at the end of a line in the file

[root@centos01 t1019]# sed -r 's/(^f.*)/\1 888/' test.txt
ert
fff 888
**
[abcfd]
123
324
444
[rty]
**
fgfgf 888
Test line.

Delete the next line to the last line of a keyword

Scenario 1:

[root@centos01 t1019]# sed -i '/\[rty\]/{p;:a;N;$!ba;d}' test.txt 
[root@centos01 t1019]# cat test.txt 
ert
fff
**
[abcfd]
123
324
444
[rty]

Define a label a, match [rty], then N adds the next line to the schema space, matches the last line, then exits the label loop, and then commands d to clear all the content in the schema space.
if matches "[rty]"
:a
Add the next line
if mismatch "$"
goto a
Finally, exit the loop and delete the d command.

Option two:

[root@centos01 t1019]# sed -r '/\[rty\]/,$'d test.txt 
ert
fff
**
[abcfd]
123
324
444

Print lines m to n containing a string

[root@centos01 t1019]# cat -n test.txt 
     1	ert
     2	fff
     3	**
     4	[abcfd]
     5	123
     6	324
     7	444
     8	[rty]
     9	fgfgf
    10	Test line.
[root@centos01 t1019]# sed -n '1,5{/f/p}' test.txt 
fff
[abcfd]
[root@centos01 t1019]# sed -n '1,10{/f/p}' test.txt 
fff
[abcfd]
fgfgf

Posted by binarymonkey on Mon, 28 Jan 2019 02:45:14 -0800