jwen
jwen

Reputation: 79

how to replace a specific char in a file

I want to replace a specific char in a file. for example, I have a 20 line file and I want to replace the letter a on the 5th line and 12th column. example: what I have on line 5 hello world! and I want to replace the ! with ?

This cannot be done with a search and replace method because the actual text in the file is more or less random or changes frequently. I need to specify the unknown char at line 5 column 12, then replace

Upvotes: 0

Views: 144

Answers (1)

mattb
mattb

Reputation: 3053

Edit - better answers than mine:

From @Cyrus:

sed -E '5 s/(.{11})./\1?/' your_file

From @potong:

sed '5s/./?/12' your_file

My original answer (just to contrast with the cleaner approaches)

This will do it:

sed '5 s/\(.\{11\}\).\(.*\)/\1?\2/' your_file

The ways it's working is as follows:

  • On line 5, perform a substitution
  • I remember the stuff in between the above using \( and \)
  • The first remembered part matches 11 characters of any type .\{11\}
  • Then a single characters of any type is matched (in your case that will be the '!')
  • The second remembered part matches everything after the single character\{.*\}
  • Then we put back the remembered content \1 and \2
  • But we replace the single matched character with a question mark

Once you've confirmed it does what you want, you can add the -i to do the substitution in-place:

sed -i '5 s/\(.\{11\}\).\(.*\)/\1?\2/' your_file

If we use the extended expressions flag (-E) we don't have to escape so much stuff:

sed -E '5 s/(.{11}).(.*)/\1?\2/' your_file

Upvotes: 2

Related Questions