Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk-substitution pattern

Tags:

awk

I have two sample files:

file1:

Bolek
jeden(wzór1)
Lolek
dwa(wzór2)
trzy(wzór3)

file2:

czerwony
zielony
niebieski

I tried the command:

awk '{while(getline a < "file2"); sub(/wzór1/, a); print }' file1
Bolek
jeden(niebieski)
Lolek
dwa(wzór2)
trzy(wzór3)

I want to replace wzór1 of "file1" on the contents of "file2". I want to print:

Bolek
jeden(czerwony
zielony
niebieski)
Lolek
dwa(wzór2)
trzy(wzór3)
like image 554
Tedee12345 Avatar asked Jan 15 '23 17:01

Tedee12345


2 Answers

One way:

$ awk -v val="$(<file2)" '{sub(/wzór1/,val);}1' file1
Bolek
jeden(czerwony
zielony
niebieski)
Lolek
dwa(wzór2)
trzy(wzór3)

The content of file2 is read into a variable "cont". This variable is passed to awk and all the occurence of wzor1 is replaced with the variable content.

like image 53
Guru Avatar answered Mar 07 '23 19:03

Guru


awk 'NR==FNR{r=r s $0; s=ORS; next} {sub(/wzór1/,r)} 1' file2 file1

Assuming you are on UNIX, here's the difference between the approaches in the 2 posted solutions so far, note the empty line at the end of "file2":

$ cat file2
czerwony
zielony
niebieski

$ awk 'NR==FNR{r=r s $0; s=ORS; next} {sub(/wzr1/,r)} 1' file2 file1
Bolek
jeden(czerwony
zielony
niebieski
)                   <--- note the empty line is reproduced
Lolek
dwa(wzr2)
trzy(wzr3)
$ awk -v val="$(<file2)" '{sub(/wzr1/,val);}1' file1
Bolek
jeden(czerwony
zielony
niebieski)          <--- note the empty line has been removed
Lolek
dwa(wzr2)
trzy(wzr3)

If you're not on UNIX then the shell solution would be N/A anyway I assume.

like image 22
Ed Morton Avatar answered Mar 07 '23 17:03

Ed Morton