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

时间:2018-06-01 19:11:50

标签: 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来执行相同的操作?感谢

2 个答案:

答案 0 :(得分:0)

您可以在awk中执行以下操作:

awk '/^#/{bumpcase=$4}/^[^#]/{print $0":"bumpcase}' yourfile

示例:

$ cat test.txt
#bumpcase case ( BUMPCASE45678 ) some other text
fred fredm1989

chasi chasi1987

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

roger roger1985

$ awk '/^#/{bumpcase=$4}/^[^#]/{print $0":"bumpcase}' test.txt
fred fredm1989:BUMPCASE45678
chasi chasi1987:BUMPCASE45678
hector hector1978:BUMPCASE45678
simon sim1984:BUMPCASE3123098
roger roger1985:BUMPCASE3123098

答案 1 :(得分:0)

编辑: 由于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.

解决方案第二: 如果您想在输出中保留空行。

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.