5

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?

8
awk '{
  s = m = ""
  for (i = 3; i < NF; i++) {m = m s $i; s = "_"}
  if (m == "") m = "_"
  print $1, $2, m, $NF}'
4

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
'

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.