Home > Net >  sed replacing first occurence of characters in each line of file only if they are first 2 characters
sed replacing first occurence of characters in each line of file only if they are first 2 characters

Time:03-30

Is it possible using sed to replace the first occurrence of a character or substring in line of file only if it is the first 2 characters in the line?

For example we have this text file:

15 hello
15 h15llo
1 hello
1 h15loo 

Using the following command: sed -i 's/15/0/' file.txt

Will give this output

0 hello
0 h15llo
1 hello
1 h0loo 

What I am trying to avoid is it considering the characters past the first 2. Is this possible?

Desired output:

0 hello
0 h15llo
1 hello
1 h15loo 

CodePudding user response:

Try:

sed -i 's/15 /0 /' file.txt

(With spaces)

  • Related