【问题标题】:Find section in a file and append at the bottom of the section在文件中查找部分并附加到部分底部
【发布时间】:2014-12-10 00:52:58
【问题描述】:

我正在尝试在 bash 中找到一种在文件的一部分中包含一行的方法。

特别是,如果我有这样的部分:

%salary
1213
3344
23343
33
%end

%employees
joe
mark 
adam 
%end

我想在员工部分的 %end 部分之前的员工部分的上述文件中添加一个新员工(例如,乔治)。

如何在 bash 中做到这一点?

【问题讨论】:

  • 有人知道 sed 解决方案吗?

标签: bash shell sed


【解决方案1】:

这可能对你有用(GNU sed):

sed -e '/%employees/,/%end/{/%end/iGeorge' -e '}' file

%employee .. %end 之间的范围内的%end 之前插入George

N.B 程序必须使用 2 个语句,因为 i 命令由换行符终止。使用 Bash 的替代方法是:

sed $'/%employees/,/%end/{/%end/iGeorge\n}' file

【讨论】:

    【解决方案2】:

    在这种情况下使用awk(3) 可能是最简单的:

    /%employees/ { INSERT=1 }
    
    /%end/ {
        if (INSERT == 1) print "george"
        INSERT=0
    }
    
    { print $0 }
    

    例子:

    $ awk -f script input 
    %salary
    1213
    3344
    23343
    33
    %end
    
    %employees
    joe
    mark 
    adam 
    george
    %end
    

    【讨论】:

      【解决方案3】:

      另外两种 awk 方式

      awk '/%employees/||p&&/%end/{p=!p;if(!p)print "George"}1' file
      

      awk '/%employees/,/%end/{if(/%end/)print "George"}1' file
      

      【讨论】:

        【解决方案4】:

        在 Perl 中,我会像下面这样。

        $ perl -00pe 's/(?s)((?:^|\n)%employees.*?)(?=%end)/\1george\n/g' file
        %salary
        1213
        3344
        23343
        33
        %end
        
        %employees
        joe
        mark 
        adam 
        george
        %end
        

        【讨论】:

          【解决方案5】:

          使用 GNU awk

          awk -v RS= -vFS='\n' -vOFS='\n' '/^%employees/{$NF="george\n"$NF};
            {printf "%s%s", $0, RT}' file
          %salary
          1213
          3344
          23343
          33
          %end
          
          %employees
          joe
          mark     
          adam 
          george
          %end
          

          【讨论】:

          • 如果您将RT 更改为ORS ORS,您将获得一个不需要gnu awk 的解决方案,但您会在末尾获得一个额外的空行。
          猜你喜欢
          • 1970-01-01
          • 2020-03-06
          • 1970-01-01
          • 1970-01-01
          • 2013-06-06
          • 1970-01-01
          • 1970-01-01
          • 2014-11-27
          • 1970-01-01
          相关资源
          最近更新 更多