GNU Awk 5.1.0. zsh, Ubuntu 22.04
I have file containing 1 record
record_grab.tmp
XJZT+ML+SD | 9979 | 4¾ | 14
and file
table.txt
| formula | no. | dose | days |
| --------------------- | --- | -------- | ------- |
| | | | |
I want to place fields 1,2,3,4 from record_grab.tmp in fields 1,2,3,4 of record 3 of table.txt. Preserving the formatting and record separators of table.txt.
I have used the chain of commands in the terminal as follows:
awk '{a[FNR]=$0}' /tmp/record_grab.tmp
|awk -v FS='|' -v OFS='|' 'FNR==NR{a[FNR]=$0; next} {print $1,$2,$3,$4 a[FNR], $3}' /tmp/record_grab.tmp /home/table.txt
The result was:
| formula | no. | dose XJZT+ML+SD | 9979 | 4¾ | 14 | no.
| --------------------- | --- | -------- | ---
| | |
The expected result is:
| formula | no. | dose | days |
| --------------------- | --- | -------- | ------- |
| XJZT+ML+SD | 9979 | 4¾ | 14 |
I realise there is definitely a more elegant way to do this, that aside I have made a mistake in my use of arrays it looks like it's put the entire line from the temp file into field 3 of table.txt rather than record 3 somehow and I can't work out how to correct it. Any help is appreciated.
I would harness GNU
AWKfor this task following way, letfile.txtcontent bethen
gives output
Explanation: I inform GNU
AWKthat pipe is both field separator (FS) and output field separator (OFS), for 2nd line I print desired columns encased in|. Then for each selected column I use dynamicsprintfto get string consisting of as many spaces as there characters in given column, which I then globally substitute using dashes. Iprintit in some manner as headers line. For each line after 2nd line and havingJohn Doeinside 1st field Iprintdesired column encased in|.(tested in GNU Awk 5.1.0)