首页 > 解决方案 > 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?

标签: sed

解决方案


根据要求将评论转移到答案中。

替换's/.*AP\(.*\)_.*/\1AP/p'放在AP匹配的内容之后 ( \1)。你大概需要's/.*AP\(.*\)_.*/AP\1/p'.

此外,.*应该[^_]*防止贪婪影响您的结果(AP3例如,如果后面的随机文本包含下划线)。因此,为了安全起见,您可能应该使用:

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

推荐阅读