user3823859
user3823859

Reputation: 469

Multiple pattern matching

I have an input file with columns seperated by | as follows.

[3yu23yuoi]|$name
!$fjkdjl|[kkklkl]
$hjhj|$mmkj

I want the output as

0          $name
!$fjkdjl     0
$hjhj      $mmkj  

Whenever the string begins with $ or !$ or "any", i want it to get printed as such else 0. I have tried the following command.It prints verything same as input file only.

awk -F="|" '{if (($1 ~ /^.*\$/) || ($1 ~ /^.*\!$/) || ($1 ~ /^any/)) {print $1} else if ($1 ~ /^\[.*/){print "0"} else if (($2 ~ /^.*\$/) || ($2 ~ /^.*\!$/) || ($2 ~ /^any/)) {print $2} else if($2 ~ /^\[.*/){print "0"}}' input > output

Upvotes: 0

Views: 42

Answers (1)

Jotne
Jotne

Reputation: 41456

This should do:

awk -F\| '{$1=$1;for (i=1;i<=NF;i++) if ($i!~/^(\$|!\$|any)/) $i=0}1' file
0 $name
!$fjkdjl 0
$hjhj $mmkj

If data does not start with $ !$ or any, set it to 0

Or if you like tab as separator:

awk -F\| '{$1=$1;for (i=1;i<=NF;i++) if ($i!~/^(\$|!\$|^any)/) $i=0}1' OFS="\t" file
0       $name
!$fjkdjl        0
$hjhj   $mmkj

$1=$1 make sure all line have same output, even if no data is changed.

Upvotes: 1

Related Questions