txt data delimited with multiple | extraction data with awk

Viewed 61

I have a file of data with | as delimiter like this with multiple same delimited rows. Here is example of 3 rows:

LOW|||IregularFeature|ENS0111548|promotor||||||||||rs4564187963|
HIGH|||IregularityFeature|ENS0dse58|exon||||||||||rs456456187992|
MODIFIER|||Iregular|ENS0111548|promotor||||||||||rs4564187963|

I wanted the data extract all data with awk into columns tab separated format (every space between fields below is a tab character):

LOW     IregularFeature ENS0111548      promotor        rs4564187963
HIGH    IregularityFeature      ENS0dse58       exon    rs456456187992
MODIFIER        Iregular        ENS0111548      promotor        rs4564187963

I tried to set delimiter in output to tab and with if conditional and for loop pick up the data:

awk 'BEGIN{FS="|",OFS="\t"}; for(i = $1; i <= $NF; i ++);if(i!= ""){print i}'
2 Answers

I would use GNU AWK for this task following way, let file.txt content be

|Hi|||name||||
|Ha|||SA||||

then

awk 'BEGIN{FPAT="[^|]+";OFS="\t"}{$1=$1;print}' file.txt

output

Hi  name
Ha  SA

Explanation: I inform GNU AWK that field is one or more (+) characters which are not (^) pipe (|) and output field separator is tab. For every line do $1=$1 (in order to trigger string rebuild) and print such line

(tested in gawk 4.2.1)

Using any awk in any shell on every Unix box:

$ awk -F'[|]+' -v OFS='\t' '{sub(/\|$/,""); $1=$1}1' file
LOW     IregularFeature ENS0111548      promotor        rs4564187963
HIGH    IregularityFeature      ENS0dse58       exon    rs456456187992
MODIFIER        Iregular        ENS0111548      promotor        rs4564187963

If that's not all you need then edit your question to clarify your requirements and provide more truly representative sample input/output including cases where that doesn't work.

Related