9

I am interested in adding a string chr to the beginning of column in each line.

The file is tab delimited and looks something like:

re1 1   AGT
re2 1   AGT
re3 2   ACGTCA
re12    3   ACGTACT

what I need is:

re1 chr1    AGT
re2 chr1    AGT
re3 chr2    ACGTCA
re12    chr3    ACGTACT

The solution can be a bash one-liner

user438383
  • 5,716
  • 8
  • 28
  • 43
Irek
  • 439
  • 1
  • 8
  • 17

3 Answers3

16

What about this?

$ awk '$2="chr"$2' file
re1 chr1 AGT
re2 chr1 AGT
re3 chr2 ACGTCA
re12 chr3 ACGTACT

Explanation

With $2="chr"$2 we add chr to the 2nd field. Then we do not need any other command to get the desired output, as the default behaviour of awk is print $0.

To make sure the OFS (output field separator) is a tab, you can do the following:

$ awk 'BEGIN{OFS="\t"}$2="chr"$2' file
re1     chr1    AGT
re2     chr1    AGT
re3     chr2    ACGTCA
re12    chr3    ACGTACT
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Good that it worked to you, @Irek! Remember you can mark one of the answers as accepted if your issue is already solved. Greetings – fedorqui Aug 05 '13 at 15:30
4

Awk one-liner do?

$ awk -v OFS=$'\t' '{ $2="chr" $2; print}' so.txt
re1     chr1    AGT
re2     chr1    AGT
re3     chr2    ACGTCA
re12    chr3    ACGTACT
MattH
  • 37,273
  • 11
  • 82
  • 84
  • How would you do this for EVERY column after the first column. Would the code change if the number of columns varies for each row? – Sky Scraper Mar 07 '21 at 18:08
1

sed one-liner:

sed 's/\<[0-9]\>/chr&/' < input > output
mohit
  • 5,696
  • 3
  • 24
  • 37