Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add string in each line at the begining of column

Tags:

string

bash

awk

I digged many threads, but neither of them adresses this question as it stands.

I am interested in addind string chr to the begining of column in each line. File is tab delimited, looks sth 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

Can be in bash oneliner

many thanks for any help, cheers, Irek

like image 497
Irek Avatar asked Aug 05 '13 15:08

Irek


People also ask

How do you add a string at the beginning of each line in Linux?

The sed command can be used to add any character of your choosing to the beginning of each line. This is the same whether you are adding a character to each line of a text file or standard input.

How do I insert a word at the beginning of a line in Linux?

Insert. Insert text to the left of the cursor by typing i from command mode. Type I to insert text at the beginning of a line.

How do you append a string to every line in Unix?

begin--fr.a2dfp.net--end begin--m.fr.a2dfp.net--end begin--mfr.a2dfp.net--end begin--ad.a8.net begin--asy.a8ww.net--end begin--abcstats.com ... The string is added only in certain lines and not in others.

How do you go to the beginning of a line in the shell?

Ctrl - x - Ctrl - x lets you go to the first character of the line for any readline-compatible environment like Bash, python and mysql.


3 Answers

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
like image 114
fedorqui 'SO stop harming' Avatar answered Oct 05 '22 12:10

fedorqui 'SO stop harming'


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
like image 21
MattH Avatar answered Oct 05 '22 12:10

MattH


sed one-liner:

sed 's/\<[0-9]\>/chr&/' < input > output
like image 23
mohit Avatar answered Oct 05 '22 12:10

mohit