Hi All,
I'm trying to get part of a filename and my skill with regular expression are lacking. I know I need to use SED but have no idea how to use it. I'm hoping that someone can help me out. The file names would be:
prefix<partwewant>suffix.extension
the prefix and suffix are always 3 characters and always the same [ABC, XYZ]. eg.
ABCN204867362XYZ.jpg
ABCC2039458XYZ.jpg
ABC2049583XYZ.jpg
Any ideas on how I can extract the middle part of the name?
Thanks in advance
$ sed -e 's/.*ABC//' -e 's/XYZ.*//' test
N204867362
C2039458
2049583
$ cat test
ABCN204867362XYZ.jpg
ABCC2039458XYZ.jpg
ABC2049583XYZ.jpg
1 Like
Thanks heaps itkamaraj.
Based on your command, how can I add back the file extension?
Using standard parameter expansion:
for f in ABC*XYZ.*; do
_t=${f#???} _e=${_t#${_t%%???.*}}
printf 'middle:\t%s\n' "${_t%$_e}"
printf 'ext:\t%s\n' "${_e#???}"
done
Example output:
% ls -l
total 0
-rw-r--r-- 1 sysadmin None 0 Jul 22 11:41 ABC2049583XYZ.jpg
-rw-r--r-- 1 sysadmin None 0 Jul 22 11:42 ABCC2039458XYZ.png
-rw-r--r-- 1 sysadmin None 0 Jul 22 11:41 ABCN204867362XYZ.jpg
% for f in ABC*XYZ.*; do
_t=${f#???} _e=${_t#${_t%%???.*}}
printf 'middle:\t%s\n' "${_t%$_e}"
printf 'ext:\t%s\n' "${_e#???}"
done
middle: 2049583
ext: .jpg
middle: C2039458
ext: .png
middle: N204867362
ext: .jpg
$ sed -e 's/.*ABC//' -e 's/XYZ.*/.jpg/' test