Insert field between two fields using awk or sed

Hi All,

I am trying to insert two columns in the following text. I tried awk but failed to achieve. Highly appreciate your help


DATETIME="28-Sep-2013;20:09:08;"
CONTROL="AB"

echo "Myfile.txt;11671;7824.90;2822.48" 

The DATETIME will be inserted at the beginning and CONTROL will be inserted between field 1 and 2.

The output will be as below:


28-Sep-2013;20:09:08;Myfile.txt;AB;11671;7824.90;2822.48

I will be using variable to get date and time and the value AB.

Thanks
Angshuman

Hi,
In shell:

DATETIME="28-Sep-2013;20:09:08;"
CONTROL="AB"
echo "Myfile.txt;11671;7824.90;2822.48" | ( IFS=\; read a b c d ; echo "$DATETIME$a;$CONTROL;$b;$c;$d")

Regards.

Hi disedorgue,

Thank you for your reply. This is working fine in shell. However it is my mistake that I did not mention the expected end result completely. I have a file which contains some data with pipe as separator. I need to extract the data from the file and then insert the fields as mentioned above. I am using the following:

awk  -F'|' 'BEGIN{OFS=";";} {print $1,$11,$12,$16;}' $SUCCESSFILE 

This is why I wanted to use awk or sed. May be something like following:

awk  -F'|' 'BEGIN{OFS=";";} {print $1,$11,$12,$16;}' $SUCCESSFILE  | awk/sed command to insert field

Thanks
Angshuman

Ok, you can do it with awk as this example:

$ DATETIME="28-Sep-2013;20:09:08;"
$ CONTROL="AB"
$ echo "Myfile.txt|11671|7824.90|tttt|2822.48|xxx|yyy" | awk -F'|' -v d=$DATETIME -v c=$CONTROL 'BEGIN{OFS=";";} {print d$1,c,$2,$3,$5;}'
28-Sep-2013;20:09:08;Myfile.txt;AB;11671;7824.90;2822.48

Beware: you must concat variable d and $1 because end d is already ";"

Otherwise, technically, it's possible with shell solution but most slow:
Example:

$ echo "Myfile.txt|11671|7824.90|tttt|2822.48|xxx|yyy" | ( IFS=\| read a b c d e f g; echo "$DATETIME$a;$CONTROL;$b;$c;$e")
28-Sep-2013;20:09:08;Myfile.txt;AB;11671;7824.90;2822.48

Regards.

1 Like

You don't need two awk cmds connected through a pipe; do it in one go:

awk -F'|' -v DT=$DATETIME -v CTL=$CONTROL 'BEGIN{OFS=";"} {print DT,$1,CTL,$11,$12,$16;}' $SUCCESSFILE
1 Like