0

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

99999bbbbbt999999bbt99t99t99t99

(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 '15 at 20:34
2
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 '15 at 20:11
  • @Costas, that would remove spaces at the beginning of the line which is not what was asked for AFAICT. – Stéphane Chazelas Oct 23 '15 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.