使用Awk / Sed替换文件中匹配模式的值

希罗普

我在配置文件中有以下输入

#bumpcase case ( BUMPCASE45678 ) some other text
fred fredm1989

chasi chasi1987

hector hector1978
#bumpcase case ( BUMPCASE3123098 ) some other text
simon sim1984

roger roger1985

我需要在新文件中显示内容,如下所示

fred fredm1989:BUMPCASE45678

chasi chasi1987:BUMPCASE45678

hector hector1978:BUMPCASE45678

simon sim1984:BUMPCASE3123098

roger roger1985:BUMPCASE3123098

有什么办法可以使用awk / sed执行相同的操作吗?谢谢

RavinderSingh13

编辑:由于OP现在告诉字符串的字段号可能不同,所以我在BUMPCASE这里以数字开头的行中查找数字#

awk '/^#/ && match($0,/BUMPCASE[0-9]+/){val=substr($0,RSTART,RLENGTH);next} NF{$NF=$NF":"val} NF' Input_file

以下内容awk可能会对您有所帮助。

解决方案1:如果要删除空行。

awk '/^#/{val=$4;next} NF{$NF=$NF":"val} NF'  Input_file

说明:

awk '
/^#/{           ##Checking condition if a line starts from #(hash) then do following.
  val=$4;       ##Assigning a variable named val to 4th field value in current line.
  next}         ##next keyword will skip all further statements from here.
NF{             ##NF is a condition which checks if a line is NOT NULL then do following.
  $NF=$NF":"val}##Appending colon and value of variable val here to last field of line.
NF              ##NF condition checks if a line is NOT NULL then print the current line.
' Input_file    ##Mentioning Input_file name here.

解决方案2nd:如果要在输出中保留空行。

awk '/^#/{val=$4;next} NF{$NF=$NF":"val} 1'  Input_file

说明:

awk '
/^#/{           ##Checking condition if a line starts from #(hash) then do following.
  val=$4;       ##Assigning a variable named val to 4th field value in current line.
  next}         ##next keyword will skip all further statements from here.
NF{             ##NF is a condition which checks if a line is NOT NULL then do following.
  $NF=$NF":"val}##Appending colon and value of variable val here to last field of line.
1               ##awk works on method of condition and action so putting 1 making condition TRUE so print of line will happen.
'  Input_file   ##Mentioning Input_file name here.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章