sed - 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?
解决方案
根据要求将评论转移到答案中。
替换's/.*AP\(.*\)_.*/\1AP/p'
放在AP
匹配的内容之后 ( \1
)。你大概需要's/.*AP\(.*\)_.*/AP\1/p'
.
此外,.*
应该[^_]*
防止贪婪影响您的结果(AP3
例如,如果后面的随机文本包含下划线)。因此,为了安全起见,您可能应该使用:
sed -n 's/.*AP\([^_]*\)_.*/AP\1/p'
推荐阅读
- swift - 将字符串解析为 Swift 中的对象
- angular - 使用 Angular frondend 从多个服务器获取数据
- python - 如何使用 BeautifulSoup 进行刮痧
- wordpress - wordpress 上传的图片给出了损坏的链接图片
- java - 为什么 Spring Pageable 返回意外结果?
- python - Django Python mod_wsgi:ImportError:没有名为“django”的模块
- sql - 存储过程存在填充记录集的问题
- c# - 是 IQueryable 和 IQueryable
异步? - google-app-engine - Cloud Sql 二代问题
- javascript - 带有 Iron-ajax 的 Twitter API?