awk - 在特定位置插入特定文本的行

时间:2014-06-07 18:46:47

标签: text awk

我有一个文件,其中前几行以#标记开头,然后按照经典网表,也可以是以#标记开头的行。我需要在protect开始的第一行块和经典网表的第一行之间插入一行文本#。在文件的末尾,我需要插入带有单词unprotect的行。由于原始文件受保护,最好将此修改后的文本保存到具有特定名称的新文件中。

示例文件:

// Generated for: spectre
// Design library name: Kovi
// Design cell name: T_Line
// Design view name: schematic
simulator lang=spectre
global 0
parameters frequency=3.8G Zo=250
// Library name: Kovi
// Cell name: T_Line
// View name: schematic
T8 (7 0 6 0) tline z0=Zo f=3.8G nl=0.5 vel=1
T7 (net034 0 net062 0) tline z0=Zo f=3.8G nl=0.5 vel=1
T5 (net021 0 4 0) tline z0=Zo f=3.8G nl=0.5 vel=1
T4 (net019 0 2 0) tline z0=Zo f=3.8G nl=0.5 vel=1

2 个答案:

答案 0 :(得分:0)

sed

怎么样?
sed -e '/^#/,/^#/!iprotect'$'\n''$aunprotect'$'\n' input_file > new_file

在第一个注释行块之后,在一行上插入'protect',然后在末尾添加'unprotect'。

注意:因为我使用$'\n'代替文字换行符bash被假定为shell。

答案 1 :(得分:0)

由于您发布了帖子

awk 'BEGIN{ protected=""} { if($0 !~ /#/ && !protected){  protected="1"; print "protect";}  print $0}END{print "unprotect";}' input_file > output_file

一旦检测到没有#作为第一个非空白字符的行,它将输出一行protect。最后,它将为unprotect输出一行。

测试文件

#
 #
#
     #Preceded by a tab
 begin protect

#

 before unprotect

结果

#
 #
#
     #Preceded by tab
protect
 begin protect

#

 before unprotect
unprotect

修改: 删除[:space:]*,因为它似乎已默认处理。


支持//

如果您想在同一个脚本中支持#//,则正则表达式部分将更改为/#|\//必须使用/转义特殊字符\

这会检查至少一个/

添加量词{2}将完全匹配///#|\/{2}/