简体   繁体   中英

Understanding sed

I am trying to understand how

sed 's/\^\[/\o33/g;s/\[1G\[/\[27G\[/' /var/log/boot

worked and what the pieces mean. The man page I read just confused me more and I tried the info sai Id but had no idea how to work it! I'm pretty new to Linux. Debian is my first distro but seemed like a rather logical place to start as it is a root of many others and has been around a while so probably is doing stuff well and fairly standardized. I am running Wheezy 64 bit as fyi if needed.

The sed command is a stream editor , reading its file (or STDIN) for input, applying commands to the input, and presenting the results (if any) to the output (STDOUT).

The general syntax for sed is

sed [OPTIONS] COMMAND FILE

In the shell command you gave:

sed 's/\\^\\[/\\o33/g;s/\\[1G\\[/\\[27G\\[/' /var/log/boot

the sed command is s/\\^\\[/\\o33/g;s/\\[1G\\[/\\[27G\\[/' and /var/log/boot is the file.

The given sed command is actually two separate commands:

  1. s/\\^\\[/\\o33/g

  2. s/\\[1G\\[/\\[27G\\[/

The intent of #1, the s (substitute) command, is to replace all occurrences of '^[' with an octal value of 033 (the ESC character). However, there is a mistake in this sed command. The proper bash syntax for an escaped octal code is \\nnn , so the proper way for this sed command to have been written is:

s/\\^\\[/\\033/g

Notice the trailing g after the replacement string? It means to perform a global replacement; without it, only the first occurrence would be changed.

The purpose of #2 is to replace all occurrences of the string \\[1G\\[ with \\[27G\\[ . However, this command also has a mistake: a trailing g is needed to cause a global replacement. So, this second command needs to be written like this:

s/\\[1G\\[/\\[27G\\[/g

Finally, putting all this together, the two sed commands are applied across the contents of the /var/log/boot file, where the output has had all occurrences of ^[ converted into \\033 , and the strings \\[1G\\[ have been converted to \\[27G\\[ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM