rshdzrt
rshdzrt

Reputation: 135

Extract text between matched pattern and append text before the result

I have a line of code like this "some_random_text_AP3_somerandomtext".

I'm trying to extract only this AP3. Since AP is fixed all the time, I used below solution.

echo "some_random_text_AP3_somerandomtext" | sed -n 's/.*AP\(.*\)_.*/\1/p'

It is successfully returning the number which is just 3, so I used the below solution to append AP to it.

echo "some_random_text_AP3_somerandomtext" | sed -n 's/.*AP\(.*\)_.*/\1AP/p'

It is appending after 3 and the result is 3AP, I actually want to append this before 3 like AP3, but not 3AP.

Could someone point me out how to append it before?

Upvotes: 1

Views: 90

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754810

Transferring comments into an answer, as requested.

The replacement 's/.*AP\(.*\)_.*/\1AP/p' puts the AP after what was matched (\1). You presumably need 's/.*AP\(.*\)_.*/AP\1/p'.

Also, the .* should be [^_]* to prevent greediness from affecting your result (if the random text after AP3 contains an underscore, for example). So, for safety, you should probably use:

sed -n 's/.*AP\([^_]*\)_.*/AP\1/p'

Upvotes: 2

Timur Shtatland
Timur Shtatland

Reputation: 12425

You can also use grep:

echo "some_random_text_AP3_somerandomtext" | grep -Po 'AP[^_]*'         
AP3

Here, GNU grep uses the following options:
-P : Use Perl regexes.
-o : Print the matches only (1 match per line), not the entire lines.

SEE ALSO:
perlre - Perl regular expressions

Upvotes: 1

Related Questions