Search for a pattern and replace a space at specific position with a Character in File

In file, we have millions of records each of 1000 in length. And at specific position say 800 there is a space, we need to replace it with Character X if the ID in that row starts with 123.

So far i have used the below which is replacing space at that position to X but its not checking for records which have ID as 123.

awk '
    function repl(s,f,t,v)
    {
        return substr(s,1,f-1) sprintf("%-*s", t-f+1, v) substr(s,t+1)
    }

    {
        a=repl($0,800,800,"X")
        print a
    }
' infile

Thanks

perl -npi.bak -e ' s/(123.{797}) /${1}X/' infile
1 Like

Thanks for your script. After execution just .bak file got created and space remained as it is i.e. no replacement with X.

Could you pls have a look.

$ cat test.file
123andsomeothervalues with a space at position 22
Not 123 but with the  space
123 but no spacein the appropriate column

$ perl -npi.bak -e 's/^(123.{18}) /$1X/' test.file

$ cat test.file
123andsomeothervaluesXwith a space at position 22
Not 123 but with the  space
123 but no spacein the appropriate column

If the space is in position 800, then there a 799 characters before it not 800 so the quantifier should be 796 ie:

perl -npi.bak -e ' s/(123.{796}) /${1}X/' infile

Perhaps my ability to count was compromised by a dangerous caffeine deficiency, currently remedying this cU.

1 Like