Using pipe character as a field separator

后端 未结 3 1626
无人共我
无人共我 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:28

    Try to escape the |

    echo "more|data"  | awk -F\| '{print $1}'
    more
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-22 10:37

    You can escape the | as \|

    $ cat test
    hello|world
    $ awk -F\| '{print $1, $2}' test
    hello world
    
    0 讨论(0)
提交回复
热议问题