使用管道字符作为字段分隔符 [英] Using pipe character as a field separator

查看:83
本文介绍了使用管道字符作为字段分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试不同的命令来处理csv文件,其中的分隔符是竖线|字符.

I'm trying different commands to process csv file where the separator is the pipe | character.

当逗号是分隔符时,这些命令可以工作,但是当我用管道替换它时,它会引发错误:

While those commands do work when the comma is a separator, it throws an error when I replace it with the pipe:

awk -F[|] "NR==FNR{a[$2]=$0;next}$2 in a{ print a[$2] [|] $4 [|] $5 }" OFS=[|] file1.csv file2.csv

awk "{print NR "|" $0}" file1.csv

我尝试了"|"[|]/|无济于事.

I tried, "|", [|], /| to no avail.

我在Windows上使用Gawk.我想念的是什么?

I'm using Gawk on windows. What I'm I missing?

推荐答案

您尝试了"|"[|]/|. /|不起作用,因为转义字符为\,而[]用于定义字段范围,例如,如果希望FS,-,则定义[,-].

You tried "|", [|] and /|. /| does not work because the escape character is \, whereas [] is used to define a range of fields, for example [,-] if you want FS to be either , or -.

使其正常工作"|"很好,您确定以这种方式使用它吗?或者,将其转义-> \|:

To make it work "|" is fine, are you sure you used it this way? Alternativelly, escape it --> \|:

$ echo "he|llo|how are|you" | awk -F"|" '{print $1}'
he
$ echo "he|llo|how are|you" | awk -F\| '{print $1}'
he
$ echo "he|llo|how are|you" | awk 'BEGIN{FS="|"} {print $1}'
he

但是请注意,当您说:

print a[$2] [|] $4 [|] $5

因此您根本不使用任何定界符.正如您已经定义了OFS一样,请执行以下操作:

so you are not using any delimiter at all. As you already defined OFS, do:

print a[$2], $4, $5

示例:

$ cat a
he|llo|how are|you
$ awk 'BEGIN {FS=OFS="|"} {print $1, $3}' a
he|how are

这篇关于使用管道字符作为字段分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆