0

I have a file.txt that contains the single line:

[MOVING] From [/source/foo.txt] to [/dest/bar.txt] 

I would like to find a regex that basically extract the third group inside a pair of square brackets []

expecting /dest/bar.txt

So far, I came up with:

$> cat file.txt | grep ".*From.*to.*" | grep -oP '(?<=to ).*$' | cut -d "[" -f 2 | cut -d "]" -f 1 

which works but doesn't like an elegant solution at all. Does anyone have an idea on how to achieve that ?

0

3 Answers 3

1
grep -o '\[[^]]*\]$' file.txt | sed 's/\[//; s/\]//' 

This anchors the grep to the end of the line, then extracts the square brackets and desired text. The sed command strips off the brackets.

1
  • Note that this extracts the last group, not the third group. It isn't clear from the question whether this is an acceptable implementation. Commented Jun 4, 2017 at 0:44
1
$ echo "$a" [MOVING] From [/source/foo.txt] to [/dest/bar.txt] $ echo "$a" |egrep -o '\[.[^ ]+\]$' [/dest/bar.txt] 
1
  • Note that this extracts the last group, not the third group. It isn't clear from the question whether this is an acceptable implementation. Commented Jun 4, 2017 at 0:44
1

You can use cut to extract the part after the opening bracket you're interested in, and complete with sed to remove the part after the maching bracket.

cut -d '[' -f 3 | sed 's/].*//' 

Alternatively, you can do it in a single sed or awk command.

sed 's/^[^[]*\[\([^\]\)]*\][^[]*\[\([^\]\)]*\][^[]*\[\([^\]\)]*\].*$/\3/' gawk -F '(^|\\])[^[]*(\\[|$)' '{print $4}' awk '{split($0, a, "(^|\\])[^[]*(\\[|$)"); print a[4]}' 

In both awk commands, field 1 is empty because the first separator starts at the beginning of the string, so the third bracketed group is field 4.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.