Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux: extract pattern from file

Tags:

linux

sed

awk

I have a big tab delimited .txt file of 4 columns

col1    col2    col3    col4
name1   1       2       ens|name1,ccds|name2,ref|name3,ref|name4
name2   3       10      ref|name5,ref|name6
...     ...     ...     ...

Now I want to extract from this file everything that starts with 'ref|'. This pattern is only present in col4

So for this example I would like to have as output

ref|name3
ref|name4
ref|name5
ref|name6

I thought of using 'sed' for this, but I don't know where to start.

like image 601
user1987607 Avatar asked Sep 05 '26 15:09

user1987607


2 Answers

I think awk is better suited for this task:

$ awk  '{for (i=1;i<=NF;i++){if ($i ~ /ref\|/){print $i}}}' FS='( )|(,)' infile
ref|name3
ref|name4
ref|name5
ref|name6

FS='( )|(,)' sets a multile FS to itinerate columns by , and blank spaces, then prints the column when it finds the ref pattern.

like image 103
Juan Diego Godoy Robles Avatar answered Sep 08 '26 04:09

Juan Diego Godoy Robles


Now I want to extract from this file everything that starts with 'ref|'. This pattern is only present in col4

If you are sure that the pattern only present in col4, you could use grep:

grep -o 'ref|[^,]*' file

output:

ref|name3
ref|name4
ref|name5
ref|name6
like image 40
Kent Avatar answered Sep 08 '26 03:09

Kent