获取sed中过滤部分的第一个字母

我有一个文件名,例如 15736--1_brand-new-image.jpg

My goal is to get the first letter after the _ in this case the b.

With s/(.*)_(.*)$/2/ I am able to extract brand-new-image.jpg

which is partly based on the info found on https://www.oncrashreboot.com/use-sed-to-split-path-into-filename-extension-and-directory

I've already found get first letter of words using sed but fail to combine the two.

To validate my sed statement I've used https://sed.js.org/

How can I combina a new sed statement on the part I've filtered to get the first letter?

回答

使用您展示的样品,您可以尝试以下操作。

echo "15736--1_brand-new-image.jpg" | sed 's/[^_]*_(.).*/1/'

说明:简单地使用 的替换操作sed,然后查找直到第 1 次出现,_然后将下一个 1 个字符保存到反向引用中并提及 .* 将覆盖它之后的所有内容,同时简单地用第一个反向引用值替换所有内容,该值将在第 1 个 _ 之后案例其b.

说明:以下仅作说明之用。

sed '            ##Starting sed program from here.
s/               ##using s to tell sed to perform substitution operation.
[^_]*_(.).*    ##using regex to match till 1st occurrence of _ then using back reference (.) to catch value in temp buffer memory here.
/1/             ##Substituting whole line with 1st back reference value here which is b in this case.
'


以上是获取sed中过滤部分的第一个字母的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>