How to set field separator as ^@ (special characters) in AWK?

Viewed 583

I have a record in this format.

^@343453^@145562998^@1001^@1KDI03K^@1802282^@10^@118543r221^@10^@1k2FOOD^@1NB^@1^@4554545^@3444545^@1STD^@45454554^@1NORMAL^@1^@1^@1^@1CDIH^@1^@12PY567

Here field separator is ^@ and the file has a total of 73 fields

I have tried

awk -F "^@" ' { print $1} ' file.txt;
awk -F "\^\@" ' { print $1} ' file.txt;

But I can not get my fields separated I am getting the whole record as output.

What is the correct way of doing this?

2 Answers

You need to double escape ^ in your field separator. Why you need to escape it because it has a special meaning so to make it to be treated as a literal character use this one.

awk -F'\\^@' '{print $2}'  Input_file

Your first field is empty so it can't be printed, so to know your field number with their values with your shown samples, you can try following command for better understanding of them.

awk -F'\\^@' '{for(i=1;i<=NF;i++){print "field Number:"i " field value is:" $i}}' Input_file

Few lines of your samples will be:

field Number:1 field value is:
field Number:2 field value is:343453
field Number:3 field value is:145562998
field Number:4 field value is:1001
field Number:5 field value is:1KDI03K

You may use:

awk -F '\\^@' '{print $2}' file

343453

Explanation:

  • ^ is special regex meta character that needs to be doubly escaped while @ doesn't need any escaping.
  • use print $2 instead of print $1 because you have delimiter ^@ at the start of record hence $1 or first field will be empty.
Related