Get string before specific word in UNIX

Hi All,

I'm writing unix shell script and I have these files. I need to get name before _DETL.tmp.

ABC_AAA_DETL.tmp
ABC_BBB_DETL.tmp
ABC_CCC_DETL.tmp
PQR_DETL.tmp
DEF_DETL.tmp
JKL_DETL.tmp
YUI_DETL.tmp
TG_NM_DDD_DETL.tmp
TG_NM_EEE_DETL.tmp
GHJ_DETL.tmp
RTY_DETL.tmp

output will be

ABC_AAA
ABC_BBB
ABC_CCC
PQR
DEF
JKL
YUI
TG_NM_DDD
TG_NM_EEE
GHJ
RTY

AWK can be used to get with $1...$n, but here number of words between _ delimiter is different. Can someone give me an idea?

Hello ace_friends22,

Could you please try following and let me know if this helps you.

 awk -F"_DETL" '{print $1}'   Input_file

EDIT: If you want to look for file ending with *.tmp then following may help you in same.

for file in *.tmp; do echo $file | awk -F"_DETL" '{print $1}'; done
OR
for file in *.tmp
do
     echo $file | awk -F"_DETL" '{print $1}'
done

Thanks,
R. Singh

Try

for FN in *.tmp; do echo ${FN%%_DETL*}; done

IIf there are other files in the current directory that end in .tmp , but not in _DETL.tmp , the above suggestion could produce some unwanted output. If this is a problem in your environment, you might want to try this slight modification:

for FN in *_DETL.tmp; do echo "${FN%_*}"; done
1 Like