2

I have a file with multiple columns and rows, and I need to cut the last 5 strings of my third column and print it in an extra column. For example:

1 info1 AAAAAAAAAAA
2 info23 TTTTTTTTTT
3 ingo45  ATATATATATATAT
4 info67 GGGYYYYUUUUUUU

My output will be:

1 info1 AAAAAAAAAAA AAAAA
2 info23 TTTTTTTTTT TTTTT
3 ingo45  ATATATATATATAT TATAT
4 info67 GGGYYYYUUUUUUU UUUUU

I was able to cut just the third column only by:

cat input_file | cut -f3 | grep -o '.\{5\}$' > output_file

But I want to maintain my original table. Any suggestion?

2

Short AWK approaches:

awk '{ $(NF+1)=substr($NF, length($NF)-4) }1' input-file
  • $NF - the last field value

  • $(NF+1) - becomes the last field (following the initial last field $NF)

  • length($NF)-4 - obtaining the starting position/offset for the 5-character slice


The output:

1 info1 AAAAAAAAAAA AAAAA
2 info23 TTTTTTTTTT TTTTT
3 ingo45 ATATATATATATAT TATAT
4 info67 GGGYYYYUUUUUUU UUUUU

----------

The same can be reached via string substitution:

awk '{ sub(/.{5}$/, "& &") }1' input-file
  • /.{5}$/ - match the last 5 chars at the end of the record

  • & - points to the whole matched sequence

  • The first solution is perfect, because sometimes I have less than 5 strings for some rows, and using the second suggestion the output was mixed between different columns when I have less than 5 strings. Thanks for the explanations! – Paul Oct 11 '17 at 20:10
1

Using two instances of the sed & replacement string:

$ sed 's/.\{5\}$/& &/' file
1 info1 AAAAAAAAAAA AAAAA
2 info23 TTTTTTTTTT TTTTT
3 ingo45  ATATATATATATAT TATAT
4 info67 GGGYYYYUUUUUUU UUUUU

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.