all_techie
all_techie

Reputation: 2959

Extract field after colon for lines where field before colon matches pattern

I have a file file1 which looks as below:

tool1v1:1.4.4
tool1v2:1.5.3
tool2v1:1.5.2.c8.5.2.r1981122221118
tool2v2:32.5.0.abc.r20123433554

I want to extract value of tool2v1 and tool2v2 My output should be 1.5.2.c8.5.2.r1981122221118 and 32.5.0.abc.r20123433554.

I have written the following awk but it is not giving correct result:

awk -F: '/^tool2v1/ {print $2}' file1
awk -F: '/^tool2v2/ {print $2}' file1

Upvotes: 0

Views: 1512

Answers (4)

0.sh
0.sh

Reputation: 2762

the question has already been answered though, but you can also use pure bash to achieve the desired result

#!/usr/bin/env bash
while read line;do
  if [[ "$line" =~ ^tool2v* ]];then
      echo "${line#*:}"
  fi
done < ./file1.txt

the while loop reads every line of the file.txt, =~ does a regexp match to check if the value of $line variable if it starts with toolv2, then it trims : backward

Upvotes: 0

sorak
sorak

Reputation: 2633

You can filter with grep:

grep '\(tool2v1\|tool2v2\)'

And then remove the part before the : with sed:

sed 's/^.*://'

This sed operation means:

^ - match from beginning of string
.* - all characters
up to and including the :

... and replace this matched content with nothing.

The format is sed 's/<MATCH>/<REPLACE>/'

Whole command:

grep '\(tool2v1\|tool2v2\)' file1|sed 's/^.*://'

Result:

1.5.2.c8.5.2.r1981122221118
32.5.0.abc.r20123433554

Upvotes: 2

Benjamin W.
Benjamin W.

Reputation: 52152

If you have a grep that supports Perl compatible regular expressions such as GNU grep, you can use a variable-sized look-behind:

$ grep -Po '^tool2v[12]:\K.*' infile
1.5.2.c8.5.2.r1981122221118
32.5.0.abc.r20123433554

The -o option is to retain just the match instead of the whole matching line; \K is the same as "the line must match the things to the left, but don't include them in the match".

You could also use a normal look-behind:

$ grep -Po '(?<=^tool2v[12]:).*' infile
1.5.2.c8.5.2.r1981122221118
32.5.0.abc.r20123433554

And finally, to fix your awk which was almost correct (and as pointed out in a comment):

$ awk -F: '/^tool2v[12]/ { print $2 }' infile
1.5.2.c8.5.2.r1981122221118
32.5.0.abc.r20123433554

Upvotes: 2

Chen Shabi
Chen Shabi

Reputation: 174

grep -E can also do the job:

grep -E "tool2v[12]" file1 |sed 's/^.*://'

Upvotes: 3

Related Questions