Search code examples
bashpositionuppercase

substitute a letter at a specific position in the file itself using bash


I am trying to do this:

I have a file with content like below;

file: abcdefgh

I am looking for a way to do this;

file: aBCdefgh

So,make the 2nd and 3rd letter "capital/uppercase" in the file itself, because I have to do multiple conversions at different positions in a string in the file. Can someone please help me to know how to do this?

I came to know something like this below, but it does only for a single first character of the string in the file:

sed -i 's/^./\U&/' file

output: Abcdefgh

Thanks much!


Solution

  • Change your sed approach to the following:

    sed -i 's/\(.\)\(..\)/\1\U\2/' file
    

    $ cat file
    aBCdefgh
    

    matching section:

    • \(.\) - match the 1st char of the string into the 1st captured group

    • \(..\) - match the next 2 chars placing into the 2nd captured group

    replacement section:

    • \1 - points to the 1st parenthesized group \1 i.e. the 1st char

    • \U\2 - uppercase the characters from the 2nd captured group \2


    Bonus approach for I want to capitalize "105th & 106th" characters:

    sed -Ei 's/(.{104})(..)/\1\U\2/' file