2

I have a tab-delimited text file in the following format.

Col1 | Col2 | Col3 123.0 | 534.2 | Blah0 2031/23/12 23.00 | 786.2 | Blah1 2033/01/01 12.40 | 343.0 | Blah2 2031/27/11 

I need to remove all the characters after the space from the last column. So my output would be

Col1 | Col2 | Col3 123.0 | 534.2 | Blah0 23.00 | 786.2 | Blah1 12.40 | 343.0 | Blah2 

How should I go about this using Awk or something similar?

0

1 Answer 1

4

With awk:

awk -F '\t' 'BEGIN { OFS = FS } NR != 1 { sub(/ [^ ]*$/, "", $NF) } 1' filename 

That is:

BEGIN { OFS = FS } # the output should be separated the same way as # the input NR != 1 { # in all lines except the header line: sub(/ [^ ]*$/, "", $NF) # replace the last space and everything after it } # in the last field ($NF) with the empty string # (i.e., remove it) 1 # in all lines: print. 

If there can be several spaces in the last field and you want to remove everything after the first space, use sub(/ .*/, "", $NF) instead. It wasn't entirely clear in the question what should happen in such a case.

Sign up to request clarification or add additional context in comments.

5 Comments

Note that this awk code will trim Col3 from the header.
@Helio The ` | ` and spaces surrounding them are supposed to be tabs, as I understand it. But I suppose I could put something in the answer for field names with tabs; you're right that it seems unlikely that the transformation should be done on the header line.
What about a more unix-like solution: (rev | cut -d ' ' -f 2-7 | rev) < file?
That makes a number of assumptions about the data with which I'm not entirely comfortable. One could be handled by using -f 2- instead of -f 2-7, but what if there's a line in which the last field doesn't contain a space at all? It's tabular data; awk was pretty much made for this. (Also, I disagree that awk is not unix-like, considering that it is part of POSIX :P)
Ok, you have reason :-((

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.