How does the Shell filter out the lines in the file that match a rule and the comment lines above it

  html5, question

For example, how to filter out the configuration lines of all shortcut key mappings and the comment lines immediately before it from Vim’s configuration file. vimrc?

I know that the following command can filter out the configuration lines:

sed -n '/^[^"].*<leader>/p' .vimrc

However, how to filter out all comment lines immediately in front of the line, please ask the expert to help answer, thank you!

Sed is a stream editor. Some skills are needed to solve this problem.sed -n '/^"/{H; d}; /^"/! {/<leader>/{H; x; p; s/.*//; x; d}; /<leader>/! {s/.*//; x; d}; };' vimrcShould be able to meet the requirements, sed command tutorial please seehttp://www.grymoire.com/Unix/Sed.html, detailed as follows.

sed -n '
/^"/ {
    # 匹配到注释行,附加到缓冲空间
    H
    # 删除模式空间,开始新一轮匹配
    d
}
/^"/ !{
    # 匹配到非注释行
    /<leader>/ {
        # 匹配到目标行,附加到缓冲空间
        H
        # 交换缓冲空间和模式空间
        x
        # 打印模式空间
        p
        # 清空缓冲空间
        s/.*//
        x
        # 删除模式空间,开始新一轮匹配
        d
    }
    /<leader>/ !{
        # 非目标行,清除缓冲空间
        s/.*//
        x
        # 删除模式空间,开始新一轮匹配
        d
    }
}' vimrc

Awk may be more suitable for such problems.