我有一个文件名,例如15736--1_brand-new-image.jpg
我的目标是获取 _
之后的第一个字母,在本例中是 b
。
使用 s/\(.*\)\_\(.*\)$/\2/
我能够提取 brand-new-image.jpg
部分基于在 https://www.oncrashreboot.com/use-sed-to-split-path-into-filename-extension-and-directory 上找到的信息
我已经找到了 get first letter of words using sed但未能将两者结合起来。
为了验证我的 sed 语句,我使用了 https://sed.js.org/
如何在过滤的部分组合新的 sed 语句以获得第一个字母?
最佳答案
请根据您展示的示例尝试以下操作。
echo "15736--1_brand-new-image.jpg" | sed 's/[^_]*_\(.\).*/\1/'
解释: 简单地使用 sed
的替换操作,然后查找第一个出现的 _
然后保存下一个将 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 - 在sed中获取过滤部分的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66493008/