getting the first letter of an filtered part in sed

Viewed 82

I have a filename e.g. 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?

3 Answers

With your shown samples could you please try following.

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

Explanation: Simply using substitution operation of sed, then looking till 1st occurrence of _ then saving next 1 char into back reference and mentioning .* will cover everything after it, while substituting simply substituting everything with 1st back reference value which will be after 1st _ in this case its b.

Explanation: Following is only for explanation purposes.

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.
'

Using a . or \w could also match _ in case there are 2 consecutive __

If you want to match the first word character without matching the _ you could also use

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

Output

b

This might work for you (GNU sed):

sed -nE 's/^[^_]*_[^[:alpha:]]*([[:alpha:]]).*/\1/p' file

Since this a filtering type operation use the -n option to print only when there is a positive match.

Match the first _ from the start of the line and then discard any non-alpha characters until an alpha character and finally discard any other characters.

Print the result if there is a match.

N.B. Anchoring the match to the start of the line, prevents the result containing more than one character i.e. consider the string 123_456_abc might otherwise result in 4 or 123_a.

Related