You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

awk中使用'||o||'作为多字符串分隔符时遇正则表达式错误求助

Fixing awk "illegal primary in regular expression" Error with ||o|| Delimiter

Hey there! Let's break down why you're seeing that error and get your record extraction working right away.

Why the Error Happens

When you use awk with the -F flag to set a delimiter, awk treats the delimiter as a regular expression, not a literal string. The | character is a special regex metacharacter that means "OR". When you pass ||o|| directly, awk tries to parse this as a regex and gets confused—you've got consecutive OR operators without valid expressions between them, which is invalid syntax. That's exactly what triggers the "illegal primary in regular expression" error.

Solutions to Fix the Delimiter

Here are a few reliable ways to make awk recognize ||o|| as a literal delimiter:

1. Escape the Metacharacters (Shell-Friendly Version)

Since | is a regex metacharacter, you need to escape it with a backslash (\). But because the shell also interprets backslashes, you'll need to double-escape each | when using -F directly:

awk -F '\\|\\|o\\|\\|' '{print $1, $2, $3, $4}' yourfile.txt

Or wrap the delimiter in double quotes (the shell handles one layer of backslashes):

awk -F "\\|\\|o\\|\\|" '{print $1, $2, $3, $4}' yourfile.txt

2. Set FS in awk's BEGIN Block

To avoid shell escaping headaches, define the field separator inside awk's BEGIN block. Here, you only need a single backslash per | since it's an awk string, not processed by the shell:

awk 'BEGIN{FS="\\|\\|o\\|\\|"} {print $1, $2, $3, $4}' yourfile.txt

3. Use Character Classes (GNU awk/gawk)

If you're using GNU awk (the default on most Linux systems), you can put each | inside a character class [|]—this tells awk to treat it as a literal character instead of a regex operator:

awk -F '[|][|]o[|][|]' '{print $1, $2, $3, $4}' yourfile.txt

Example Output

For your input line A||o||BCD||o||E||o||XYZ, any of the above commands will output:

A BCD E XYZ

Which is the correctly split fields you're looking for.

Quick Tip

Always remember: if your delimiter contains regex metacharacters (like ., *, +, ?, or |), you either need to escape them or use character classes to treat them as literal text.

内容的提问来源于stack exchange,提问作者Bhawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:43:22