Cut the strings from end

could you please help me.
I have below autosys jobs

01_enable_input_hol_dtpz1b
01_abc_copy_ld_sat_xxxz1
01_abc_mavcd_yyyyyxxxz1
01_abcdef_oa_xxxxxz1
01_fdgte_symbol_ddddz1
01_fsdfsd_clean_mmmhhhfz1
01_fsdfd_create_mut_marchtz1

I want to remove name after last "_" underscore
so that I get

01_enable_input_hol
001_abc_copy_ld_sat
01_abc_mavcd
01_abcdef_oa
01_fdgte_symbol
01_fsdfsd_clean
01_fsdfd_create_mut

I tried the awk using substr but not able to display required output
because these names can be long or short depending on the setup

cat abc.1 | awk '{print substr($0, length($0)-7)}'
sed 's/_[^_]*$//' abc.1

If substr must be used in awk , try:

awk '{print substr($0, 1, (match($0, "_[^_]*$") ? RSTART - 1 : length))}' abc.1

or try another awk solution:

awk -F_ 'NF<2 || NF--' OFS=_ abc.1
2 Likes
awk -F_ 'NF<2 || NF--' OFS=_ abc.1

worked :slight_smile:

1 Like

Note: decreasing NF to reduce the number of fields is not a documented feature and only works with some awk versions.

rev file | cut -d_ -f2- | rev
01_enable_input_hol
01_abc_copy_ld_sat
01_abc_mavcd
01_abcdef_oa
01_fdgte_symbol
01_fsdfsd_clean
01_fsdfd_create_mut
1 Like

Hi
How about

while read line;do echo ${line%_*};done<lefile

With any standards-conforming version of awk , one could also use:

awk -F_ '{print substr($0, 1, length - length($NF) - 1)}' file

which produces the output:

01_enable_input_hol
01_abc_copy_ld_sat
01_abc_mavcd
01_abcdef_oa
01_fdgte_symbol
01_fsdfsd_clean
01_fsdfd_create_mut

Note, however, that the 2nd line of the output differs from the output you requested:

001_abc_copy_ld_sat

If you really want the output you requested in post #1 of this thread, you're going to have to explain the conditions under which the extra leading zero is to be inserted.