3

I have a very large colon-delimited file with two columns:

dhsj fdksjdk:dndkdlkfkd
shfdosod dkjsosjd:dkj dosjeod
dhswisoaidodisbw: dhsoi wjdos
fjfdododjfideefkjso sn:fhfdkd dkdjdf 

If the first column contains a space, I need to remove it (i.e. collapse text together):

dhsjfdksjdk:dndkdlkfkd
shfdosoddkjsosjd:dkj dosjeod
dhswisoaidodisbw: dhsoi wjdos
fjfdododjfideefkjsosn:fhfdkd dkdjdf 

In other words, everything to the left of the colon needs to be stripped of spaces, and everything to the right of the colon needs to remain untouched.

I know how to use cut -d ":" f1 to pull the first column and tr -d '[[:blank:]]' to filter out space or tab characters, but then I would have to place that column back into the file and this seems like a roundabout way of doing things.

What's the most efficient way to do what I want here?

  • Can you post sample input file and the desired output? – Arkadiusz Drabczyk Dec 5 '20 at 19:18
  • @ArkadiuszDrabczyk Added. – Hashim Aziz Dec 5 '20 at 19:31
4

Like that:

$ awk -F: '{gsub(/ /, "", $1); print $1 FS $2}' FILE
dhsjfdksjdk:dndkdlkfkd
shfdosoddkjsosjd:dkj dosjeod
dhswisoaidodisbw: dhsoi wjdos
fjfdododjfideefkjsosn:fhfdkd dkdjdf
  • 1
    Perfect, thank you. I'm always amazed at how powerful awk is, I should learn it one day. – Hashim Aziz Dec 5 '20 at 20:00
  • Quick clarification, does this also strip leading spaces? – Hashim Aziz Dec 8 '20 at 0:38
  • 1
    @Prometheus: yes – Arkadiusz Drabczyk Dec 8 '20 at 19:58
  • What I suspected, thank you. – Hashim Aziz Dec 8 '20 at 20:05

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.