awk范围模式中的反向引用

awk范围模式中的反向引用,awk,backreference,Awk,Backreference,我有一个脚本,里面有一些有用的提示,可以让我提醒自己经常忘记的各种事情。目前看起来是这样的(但有更多有用的提示): 期望输出为 brett@brett:~/tmp$ ./tips tip1 tip1: actual tip tip1: tip1 for another_header 在保持 brett@brett:~/tmp$ ./tips tip_header tip_header: tip1: actual tip tip2: anoth

我有一个脚本,里面有一些有用的提示,可以让我提醒自己经常忘记的各种事情。目前看起来是这样的(但有更多有用的提示):

期望输出为

brett@brett:~/tmp$ ./tips tip1
  tip1:
    actual tip

  tip1:
    tip1 for another_header
在保持

brett@brett:~/tmp$ ./tips tip_header
tip_header:
  tip1:
    actual tip

  tip2:
    another tip

  something:
    else with \weird $characters^~

首先,让我坚持@tripleee是正确的,您应该使用适当的工具来解析yaml文件

如果你真的想使用awk,我会做一些像这样难看的事情(我试着做一个可以在任何awk版本上工作的代码):


虽然你们已经试着把问题弄清楚了,但你们能不能把预期的结果写得更清楚一些,这样就更清楚了。听起来像是在重新发明轮子。将提示保持为JSON格式,并使用jq更好地解析和提取它们,假设这是YAML,请使用
yq
。我在尝试脚本时没有相同的输出。我在运行
/tips tip1
时得到了您想要的东西,但在运行
/tips tip_header
时,默认情况下,并非在每次linux安装中都安装JSON和YAML,而是只安装了tip1信息。其目的是使用通常可用的命令。嗯,关闭,它忽略了现实世界中的情况,即“`something:\n else
”紧跟在
tip2:
,调用
tips tip`时应该包括它,因为它是
tip\u头:
块的一部分。今晚我要和它玩一玩,看看能不能把它调整到我喜欢的程度。另外,如前所述,我宁愿避免使用yaml或类似的格式,因为它们在基本系统上并不总是可用的,我希望技巧的大部分内容不依赖于缩进和“:”以外的任何特殊格式。tips文件一开始只是字符串的集合。是的,这似乎满足了我的需求。我至少有一个边缘案件,但我现在没有时间调查。谢谢。@BrettRyland再次更新,以适合您的示例。最后,我改用了
pcregrep-Mi'(\t]*)\N*?“$1”\N*?:*?^\1?$\N'@BrettRyland
这个表达式比awk更简单。
真的吗?:)我发现它更短,而不是更简单。祝你好运:
如果你写的正则表达式很难读入你的代码库,那你就错了。
brett@brett:~/tmp$ ./tips tip1
  tip1:
    actual tip

  tip1:
    tip1 for another_header
brett@brett:~/tmp$ ./tips tip_header
tip_header:
  tip1:
    actual tip

  tip2:
    another tip

  something:
    else with \weird $characters^~
#!/bin/bash
awk -v search="$1" -F '' '
    BEGIN{IGNORECASE = 1}
    (!pos_char)&&($0 ~ (search ".*:")){
    pos_char=1;
        while($pos_char==" "){
            pos_char+=1
        }
        print; next
    } 
    prev_line == "" && NF && pos_char{
        if(NF<pos_char){
            pos_char = 0; next
        }
        for(i=1; i<=pos_char; i++){
            if($i != " "){
                pos_char = 0; next
            }
        }
    }
    pos_char{prev_line=$0;print}
' << '_EOF'

tip_header:
  tip1:
    actual tip

  tip2:
    another tip
with carriage return

  something:
    else with \weird $characters^~

another_header:
  tip1:
    tip1 for another_header

_EOF
$ ./tips tip
tip_header:
  tip1:
    actual tip

  tip2:
    another tip
with carriage return

  something:
    else with \weird $characters^~

  tip1:
    tip1 for another_header

$ ./tips tip_header
tip_header:
  tip1:
    actual tip

  tip2:
    another tip
with carriage return

  something:
    else with \weird $characters^~

$ ./tips tip1
  tip1:
    actual tip

  tip1:
    tip1 for another_header

$ ./tips tip2
  tip2:
    another tip
with carriage return