Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given input like this:

x y a b c t
p q w w t
a b c d
p q r

I'd like to concatenate fields from field 3 up to but not including the last one. If field 3 is the last field, I'd like to insert a placeholder. So given the input above, this is the preferred output:

x y a_b_c t
p q w_w t
a b c d
p q _ r

The end result is that all lines will have four fields. Is this possible in awk or cut or sed, etc?

share|improve this question
up vote 8 down vote accepted
awk '{
  s = m = ""
  for (i = 3; i < NF; i++) {m = m s $i; s = "_"}
  if (m == "") m = "_"
  print $1, $2, m, $NF}'
share|improve this answer

Alternate sed version for fun:

sed -r 's/  */_/g; s/_/ /; s/_/ /  # convert all to _, unconvert 1st 2
        ts;:s; s/(.*)_/\1 / ;t     # if a trailing third exists unconvert it
        s/ / _ /2                  # else add one
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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