Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash substitute first character in every line

Tags:

bash

sed

My file looks like this:

  1 chrX_73833098_73834098
  1 chrX_73889652_73890652
  1 chrX_91194501_91195501
  1 chrX_92000157_92001157
  1 chrX_92106500_92107500

I want to replace first character "1" into 0. Wanted output is :

  0 chrX_73833098_73834098
  0 chrX_73889652_73890652
  0 chrX_91194501_91195501
  0 chrX_92000157_92001157
  0 chrX_92106500_92107500

Trying to do it with this:

sed 's/^./0/g' file

But the output is:

0     1 chrX_73833098_73834098
0     1 chrX_73889652_73890652
0     1 chrX_91194501_91195501
0     1 chrX_92000157_92001157
0     1 chrX_92106500_92107500

I believe there is easy way to fix it, but I don't know it.

like image 901
pogibas Avatar asked Apr 13 '12 11:04

pogibas


2 Answers

There is whitespace character at the begging of each line.

you can try:

sed 's/^\s*./0/g' file

\s - match white space characters

output:

0 chrX_73833098_73834098
0 chrX_73889652_73890652
0 chrX_91194501_91195501
0 chrX_92000157_92001157
0 chrX_92106500_92107500

if you want to preserve whitespace characters:

sed 's/^\(\s*\)\(1\)/\10/g' file

I also have replaced here . with 1

like image 133
aleksanderzak Avatar answered Nov 15 '22 15:11

aleksanderzak


I think this is an easy way to understand. Try:

sed 's/1/0/1' file

output:

1 chrX_73833098_73834098
1 chrX_73889652_73890652
1 chrX_91194501_91195501
1 chrX_92000157_92001157
1 chrX_92106500_92107500

I want to say that the 's/partten/partten/g', the last 'g' mean the place in a line.
'1' mean the first matched, 'g' means all, also you can use '2g' which means from second to last.
Have a try.

like image 8
Laobe Avatar answered Nov 15 '22 15:11

Laobe