Solved grep or sed to search, replace on every line with GOTO

April 12, 2014 at 10:55:32
Specs: Windows 7
Im trying to come up with an approach to finding a string, using a portion of that string to insert it on lines starting with the value "GOTO" appending to end of line after removing PT's ( See example below! ) ???

EXAMPLE:
1. I would like to search for the line that starts with "TLAXIS/"
2. Extact from that string starting with the "," to eol (EX: ",-0.0841797,-0.9622495,0.2588236" )
3. Insert that value on every line in the same file starting with "GOTO" between last column and the "PT"
Note: PT & Numbers can be removed!

FROM:

SPINDL/1200
TLAXIS/,-0.0841797,-0.9622495,0.2588236
RAPID
FROM/.00000,.00000,1100.00000,.0000,.0000,1.0000
MODE/TRFORM,OFF
GOTO/.00000,.00000,1100.00000,-0.0841797,-0.9622495,0.2588236
RAPID
GOTO / -.00023, .00017, 1060.00000 PT 5
RAPID
GOTO / -410.71830, -608.89040, 1060.00000 PT 6
RAPID
GOTO / -410.71780, -608.89070, 1017.22900 PT 7

TO:

SPINDL/1200
TLAXIS/,-0.0841797,-0.9622495,0.2588236
RAPID
FROM/.00000,.00000,1100.00000,.0000,.0000,1.0000
MODE/TRFORM,OFF
GOTO/.00000,.00000,1100.00000,-0.0841797,-0.9622495,0.2588236
RAPID
GOTO / -.00023, .00017, 1060.00000,-0.0841797,-0.9622495,0.2588236
RAPID
GOTO / -410.71830, -608.89040, 1060.00000,-0.0841797,-0.9622495,0.2588236
RAPID
GOTO / -410.71780, -608.89070, 1017.22900,-0.0841797,-0.9622495,0.2588236


See More: grep or sed to search, replace on every line with GOTO

Report •

#1
April 13, 2014 at 19:50:51
✔ Best Answer
Let me know if you have any questions

#!/bin/ksh

# assumes only 1 line beginning with TLAXIS
myvar=$(grep ^TLAXIS/, from.txt|sed 's/TLAXIS\/,//')
# I am using nawk due to Solaris.  You might need awk
nawk '
{
# search for any line beginning with GOTO and having PT in it
if(/^GOTO.*PT.*/)
   {
   newstr=""  # holding var
   # search every field in the GOTO*PT line 
   for(i=1; i<=NF; i++) 
      {
      if($i == "PT")
         { # if field contains PT, add comma and replacement to the
           # holding var and stop the for loop
         newstr=newstr","v1
         break
         }
      else # append non PT field to the holding var
         newstr=newstr" " $i
      }
   print newstr
   }
else 
   print $0 
} ' v1="$myvar" from.txt



message edited by nails


Report •
Related Solutions


Ask Question