I have a multi-lined, tab-delimited file like this:


(where b=spaces, t=tabs)

Trailing spaces in the 2nd field are ok, but the trailing spaces in the 1st field need to be removed. Is there an easy way to remove the trailing spaces from just the 1st field of each line? sed/awk/tr?

  • @Stéphane Chazelas Thank you!, This was driving me crazy. The TAB=; s/ *$TAB/$TAB/ worked perfectly, and removed only the spaces before the first tab (only first field).
    – LKA
    Oct 23, 2015 at 20:34

1 Answer 1

sed $'s/ *\t/\t/' < file

would remove the spaces before the first tab. Here assuming a shell like ksh93, bash, zsh, mksh or FreeBSD sh with support for $'...' (which is scheduled for inclusion in issue 8 of the Single UNIX Specification).

Some sed implementations like GNU sed also recognise those \t directly:

sed 's/ *\t/\t/' file

Otherwise, POSIXly, you can do:

TAB=$(printf '\t')
sed "s/ *$TAB/$TAB/" file

You can also do the same with awk POSIXly:

awk '{sub(/ *\t/, "\t"); print}'
  • Why not 's/ *//'
    – Costas
    Oct 23, 2015 at 20:11
  • @Costas, that would remove spaces at the beginning of the line which is not what was asked for AFAICT. Oct 23, 2015 at 20:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .