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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With