user2269756
user2269756

Reputation: 927

Delete underscores from end phrase

I have table names that I'd like to rename : Here some examples :

AB_DC_JDZOJZD_HST_2090
AB_DC_JDZODSJOJZD_HIST_2500
AB_DC_JDZ_JJKOJZD_HIT_2050

But I want :

AB_DC_JDZOJZD
AB_DC_JDZODSJOJZD
AB_DC_JDZ_JJKOJZD

My question is : How to remove from the end of the word ?

Upvotes: 0

Views: 87

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

Just use parameter expansion in the shell:

while read word; do echo "${word%_*_*}"; done <<END
AB_DC_JDZOJZD_HST_2090
AB_DC_JDZODSJOJZD_HIST_2500
AB_DC_JDZ_JJKOJZD_HIT_2050
END
AB_DC_JDZOJZD
AB_DC_JDZODSJOJZD
AB_DC_JDZ_JJKOJZD

Upvotes: 1

Jotne
Jotne

Reputation: 41446

You can use awk

awk -F_ '{NF-=2}8' OFS="_" file
AB_DC_JDZOJZD
AB_DC_JDZODSJOJZD
AB_DC_JDZ_JJKOJZD

This removes two last field using _ as separator.

Upvotes: 0

devnull
devnull

Reputation: 123448

Assuming that you want to remove the last two fields delimited by _, you could say:

sed -r 's/(_[^_]*){2}$//' filename

For your input, it'd produce:

AB_DC_JDZOJZD
AB_DC_JDZODSJOJZD
AB_DC_JDZ_JJKOJZD

For fun, you could also use rev and cut to produce the same output:

rev filename | cut -d_ --complement -f1,2 | rev

Upvotes: 4

Related Questions