Sed to enter characters in a specific column

Can someone tell me how to insert chreach character in the first column.

file

1 34566 34765    
2 45678 45789
3 34567 34799
X 67895 66900
Y 34567 34890

file

chr1 34566 34765
chr2 45678 45789
chr3 34567 34799
chrX 67895 66900
chrY 34567 34890

I cannot figure out how to make it sed -iapplicable to a specific column. I am not good at syntax, so if you could break your explanation, I would be grateful. Also, would it be better to use awk for this?

+4
source share
6 answers

With sed:

sed 's/^/chr/' file.in > file.out

You do not need a flag -i, because you do not overwrite the input file file.in .

With awk:

awk '{print "chr"$0}' file.in > file.out
+12
source
sed 's|^|chr|' file_in > file_out

(s) (^) "chr". (|) .

+3

awk:

awk '{print "chr"$0}' file 

:

awk '{print "chr"$0}' file > tmp && mv tmp file
+1
source
sed 's/^\s*/chr/'

to make sure there’s no space before you. If you suffer, don’t need th \ s

0
source
awk '{print "chr"$0}'

Works for the file in question because there are no field separators. In this case, you can use (for example, for a channel delimited file):

awk 'BEGIN { FS = "|";OFS="|"} {$97="chr"$0;print}' 
0
source

$ cat file.in 1 34566 34765 2 45678 45789 3 34567 34799 X 67895 66900 Y 34567 34890

$ awk '$1="chr"$1 {print}' file.in chr1 34566 34765 chr2 45678 45789 chr3 34567 34799 chrX 67895 66900 chrY 34567 34890

In essence, you are redirecting the value of "chr" $ 1 back to $ 1 regardless of whether there are spaces before column 1 or not and still print the rest of the line.

0
source

All Articles