0

Hi I have a text file with thousands of lines which looks like this:

NNNNN
NNNNN
NNNNN
NNNNN

I would like to substitute based on their location coordinate all the letters within a specific range to another letter, let's say I want to replace all the N letters from range position 10 to position 13 to letter P, the output will be :

NNNNN
NNNNP
PPPNN
NNNNN

Any suggestion about the command I could use?

  • Just to remove extra thinking by future readers, you're counting positions in overall sequence, not by column number. – Jeff Schaller Jul 11 '19 at 13:27
  • 1
    Do all the columns have same width? PS. Feels like XY problem to be honest. – rush Jul 11 '19 at 13:31
0

Here's a short shell script:

#!/bin/bash
start=10
end=13
first=$(head -n 1 file)
width=${#first}
text=$(paste -sd "" file)
mod="${text:0:start-1}$(tr N P <<<"${text:start:end-start+1}")${text:end}"
grep -Eo ".{1,$width}" <<<"$mod"
NNNNN
NNNNP
PPPNN
NNNNN
1
$ tr -d '\n' <file | perl -pe 'substr($_, 9, 4, "P"x4)' | fold -w 5
NNNNN
NNNNP
PPPNN
NNNNN

This first removes all newlines from the data in the input file, then uses substr() in Perl to replace the text at offset 9 of length 4 with upper-case P. The fold utility is then used to fold the lines at five characters. There is no newline at the end of the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.