I wrote a post about how to print just the last substring of a delimited string. Instead if you’d want to delete just the last substring, and keep rest of the string intact, thats a little trickier.

Here’s how you do it.

@~$ echo "abc:cde:efg" | awk 'BEGIN {FS=ORS=":"} {for(i=1;i<NF;i++) print $i}' | sed 's/$/\n/'
abc:cde:

FS is the field separator, while ORS is the output record separator. ORS by default is the new line character \n. What we are doing here is splitting the string using awk, and then printing all but the last records i < NF. The sed statment is just adding a newline at the end.

If you want to skip the trailing delimiter, you could use the code below.

@~$ echo "abc:cde:efg" | awk 'BEGIN {FS=ORS=":"} {for(i=1;i<NF;i++) print $i}' | sed 's/:$/\n/'
abc:cde

Here the sed statement replaces the trailing : with a newline. To skip the newline, you can change the sed statement to sed 's/:$//'.

1 comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like

Error While Parsing Json using Python – TypeError: list indices must be integers, not str

Jotting this down for fellow googlers. I recently started learning a bit…

Makefile Tricks: Arithmetic – Addition, Subtraction, Multiplication, Division, Modulo, Comparison

While working on a project, I needed to do some calculations inside…