Bhawan
Bhawan

Reputation: 2491

Using multiple character string as separator in awk

I have a text file in which records are of the following format:

A||o||BCD||o||E||o||XYZ

I want to use '||o||' as the separator to get my records:

But When I use:

awk -F'||o||' '{print $1}'

I am getting the following error:

awk: illegal primary in regular expression ||o|| at |o||

Any help would be highly appreciated.

Upvotes: 4

Views: 3273

Answers (1)

LMC
LMC

Reputation: 12672

you need to escape literal pipes in a regular expression

awk -F'[|][|]o[|][|]' '{print $1}'

or

awk -F'[|]{2,2}o[|]{2,2}' '{print $1}'

The usual backslash escape is different in awk, so to use it (at least on GNU bash, version 4.3.42)

awk 'BEGIN{FS="\\|\\|o\\|\\|"} {print $1}' pipe.txt

and also this ugly syntax using the -F option

awk -F "\\\|\\\|o\\\|\\\|" '{print $1}' pipe.txt

The double escapes are well explained here.

Upvotes: 4

Related Questions