Computing.Net > Forums > Unix > Sed, search/replace w/in range

Sed, search/replace w/in range

Reply to Message Icon

Original Message
Name: hack1234
Date: February 21, 2007 at 11:09:29 Pacific
Subject: Sed, search/replace w/in range
OS: AIX 5.3
CPU/Ram: na
Model/Manufacturer: IBM
Comment:

I have a text file containing 100's of thousands of rows. For each line in the file, I want to remove the pipe | character if it exists between position 22 and position 57 on each line. All other pipe characters should remain in tact, just want them removed from positions 22 - 57. I know how to use sed to remove all pipes from the file but cannot figure out how to limit my search/replace to a range of characters. Can anyone help? Thanks!


Report Offensive Message For Removal

Response Number 1
Name: nails
Date: February 21, 2007 at 14:26:04 Pacific
Subject: Sed, search/replace w/in range
Reply: (edit)

One way is to cut each line into 3 sections, change only the second section, and glue the 3 lines back together ... No error checking:

#!/bin/ksh

while read line
do
len=$(expr "$line" : '.*') # length of line
f1="$(echo "$line" | cut -c1-21)"
f2="$(echo "$line" | cut -c22-57)"
f3="$(echo "$line" | cut -c58-$len)"
f2=$(echo "$f2"|sed 's/|//g')
printf "%s%s%s\n" "$f1" "$f2" "$f3"
done < data.file > newdata.file


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Sed, search/replace w/in range

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software