Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

2 Answers 2

up vote 7 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

 
discard

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.