Home > Blockchain >  replace a fixed position in a file with a set string
replace a fixed position in a file with a set string

Time:11-18

Hello I am looking to do the following:

file= sample.out

replace whatever text is in position 10-15 with "77777" but only on rows that start with ABC

so far I have:

cat sample.out | sed -r 's/^ABC(.{9})/\177777/'

But ABC at the beginning of the lines gets removed and 77777 gets inserted into the text position instead of replacing the existing the characters in that position.

CodePudding user response:

Without example I use this.

File: repl.txt

0000000001111111111222222222233333333333
1234567890123456789012345678901234567890
ABCDEFGH<12345>IJKLMNOPQRSTUVWXYZ======:

With this command:

$ sed -e 's/^\(ABC.\{6\}\).\{5\}\(.*\)$/\177777\2/' repl.txt
0000000001111111111222222222233333333333
1234567890123456789012345678901234567890
ABCDEFGH<77777>IJKLMNOPQRSTUVWXYZ======:

CodePudding user response:

Please try following awk program, using samples from @Arnaud's post.

awk -v newVal="77777" '/^ABC/{print substr($0,1,9) newVal substr($0,16);next} 1' Input_file

Explanation: Simple explanation would be, using awk program here. Firstly creating an awk variable named newVal which has 77777 value in it. In main program checking if line starts from ABC then printing sub strings(printing everything apart from 10th to 15th position in current line, printing new value in its place). If condition is not met(ie: line doesn't start from ABC) then print that line simply.

CodePudding user response:

This might work for you (GNU sed):

sed '/^ABC/{s/./&\n/14;T;s//\n&/10;s/\n.*\n/77777/}' file

Pattern match on ABC at the start of a line, delimit characters 10-14 (5 characters) by newlines and replace them and the characters between by a replacement string.

N.B. The delimiters used must be unique (newlines cannot be a part of any pattern space because newlines are used by sed to define the pattern space). Also delimiters must be inserted from largest to smallest as the newline(s) would upset the counting from the start of the line.


To overwrite from a specific position, use:

sed -E '/^ABC/{s/./\n&/10;T;s/$/\n77777/;:a;s/\n.(.*\n)(.)/\2\n\1/;ta;s/\n//g}' file

An alternative:

sed -E 's/^(ABC.{6}).{5}/\177777/' file
  • Related