查找文件中的部分并附加在该部分的底部

时间:2014-12-10 00:52:58

标签: bash shell sed

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

特别是,如果我有一个类似的部分:

%salary
1213
3344
23343
33
%end

%employees
joe
mark 
adam 
%end

我想在雇员的%end部分之前的员工部分中将新员工添加到上述文件(例如,george)。

我怎样才能在bash中做到这一点?

5 个答案:

答案 0 :(得分:3)

这可能适合你(GNU sed):

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

George %end之间的%employee之前插入%end

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

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

答案 1 :(得分: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

答案 2 :(得分:0)

在Perl中,我会在下面做。

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

%employees
joe
mark 
adam 
george
%end

答案 3 :(得分:0)

使用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

答案 4 :(得分:0)

另外两种方式

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

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