sed replace range of characters in each line

Hi,

I'm trying to replace a range of characters by their position in each line by spaces.

I need to replace characters 95 to 145 by spaces in each line.

i tried below but it doesn't work

sed -r "s/^(.{94})(.{51})/\ /" inputfile.txt > outputfile.txt

can someone please help me understand where I'm going wrong..

Yes: This contains syntactical errors. Would it be syntactically correct it would take the first 145 characters (in two groups, 94 and 51 chars) and replaces these by a single space.

Do the following:

sed 's/^\(.\{94\}\)\(.\{51\}\)/\1<b><b>.....51 blanks...<b>/' infile > outfile

You put the first 145 characters into two groups: "\(....\)" is a group each, the first consists of ".\{94\}" (any character, 94 times), the second similarly of 51 chars. This is replaced by: the first group ("\1"), so this is effectively unchanged, then 51 blanks. The rest of the line is left untouched. Notice, that i used "<b>" to denote a blank, otherwise it would be hard to read in the forum.

I hope this helps.

bakunin

1 Like

Many thanks bakunin :slight_smile:

Appreciate the detailed explanation, which is what i was hoping for than just an answer. your explanation helped me a lot to get my head around some basics of sed which I'm still learning.

With awk:

awk '{printf "%s%*s%s\n",substr($0,1,m-1),n-m+1," ",substr($0,n+1)}' m=95 n=145 inputfile.txt > outputfile.txt

With perl:

perl -pe 'BEGIN {$m=95; $n=145; $d=$n-$m+1} substr($_,$m-1,$d) = " " x $d' inputfile.txt > outputfile.txt
1 Like