bash 替换每一行中的第一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10140213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash substitute first character in every line
提问by PoGibas
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 :
我想将第一个字符“1”替换为 0。想要的输出是:
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.
我相信有简单的方法可以解决它,但我不知道。
回答by wisent
There is whitespace character at the begging of each line.
每行的开头都有空格字符。
you can try:
你可以试试:
sed 's/^\s*./0/g' file
\s - match white space characters
\s - 匹配空白字符
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\)//g' file
I also have replaced here . with 1
我这里也换过。与 1
回答by Laobe
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.
我想说's/partten/partten/g',最后一个'g'表示一行中的位置。
'1' 表示第一个匹配,'g' 表示全部,您也可以使用 '2g' 表示从第二个到最后一个。
试试。