Operating System - HP-UX
1831131 Members
2690 Online
110020 Solutions
New Discussion

Re: How to search/replace text based on character position

 
SOLVED
Go to solution
Dan Hardison
Advisor

How to search/replace text based on character position

I need to replace characters 11-26 with "4545454545454545" on all lines that contain "10H" in character positions 1-3. I've tried many iterations with sed, awk, grep, cut, but I'm not having much luck. Any ideas?

TIA,
Dan
4 REPLIES 4
curt larson_1
Honored Contributor
Solution

Re: How to search/replace text based on character position

cat $file |
awk -v stuff="4545" '{
x=substr($0,1,3);
if ( x ~ "10H" ) {
start=substr($0,0,10);
end=substr($0,27);
printf("%s%s%s\n",start,stuff,end);
}}'
Bhuvaneswari Selvaraj
Valued Contributor

Re: How to search/replace text based on character position

awk '
$0!~/^abc/ {print $0}
$0~/^abc/ { printf ("%s%s%s\n",substr($0,0,10),"ghi",substr($0,26,length($0)-25));}' $*

Replace the string ghi in the printf to your string 4545.... and save this in my file say myawk.

Then at the command prompt, execeute
./myawk inputfile
(myawk need to have execute permission)

HTH


Mark Grant
Honored Contributor

Re: How to search/replace text based on character position

Here is the almost inevitable perl version

cat testfile | perl -n -e 'if($_=~/^10H.*/){substr($_,10,15)="4545454545454545"};print;'
Never preceed any demonstration with anything more predictive than "watch this"
Dan Hardison
Advisor

Re: How to search/replace text based on character position

Thanks guys! Perl was my method of choice. Points assigned.

Dan