Getting the content of a string without the last column

Created by Alin Brindusescu on 2011-01-24 07:17:41

This days I need a Linux command line to extract the a part of a string without the last column.
My problem: I had, in a file, some strings like this:

 
# less test.txt
String_With_4_Columns
String_With_More_Than_4_Columns
With_Less
 
and I had to find a simple way to remove the last word after "_". This will not work with cut because the number of columns is variable so I can't specify what columns I want. The solution I had for this problem was to use awk:
 
# awk -F_ '{ print substr($0, 0, length($0) - (length($NF)==length($0)?0:length($NF) + 1)) }' test.txt
String_With_4
String_With_More_Than_4
With
 

Comments: work in progress!

Search

Ads