Using pipe character as a field separator

后端 未结 3 1640
无人共我
无人共我 2020-12-22 09:58

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 separat

3条回答
  •  悲哀的现实
    2020-12-22 10:30

    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
    

    But then note that when you say:

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

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

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

    Example:

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

提交回复
热议问题