LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed script (https://www.linuxquestions.org/questions/programming-9/sed-script-224670/)

glam1 08-31-2004 02:36 AM

sed
 
Hi,

I have a text file as follows:

Line1....... 1111ABC
Line2....... 1134ABC
Line3....... 1149ABC
Line4....... 2140ABC

I just want to replace all ABC to DEF and increment all number by 1 if the number start with 11

The output file should be:

Line1....... 1112ABC
Line2....... 1135ABC
Line3....... 1150ABC
Line4....... 2140ABC

Can anyone tell me how to write a sed script to handle this case?


Thank

cdlen 08-31-2004 04:56 AM

I'm no sed guru but i see a problem with the increment operation. Afik sed doesn't do maths. And it's not just a matter of replacing 1 with2, 2 with 3,... , there is the question of the carry on.
My way out of that would be to use a scripting langage with regular expressions.
Here is my suggestion in Python:

Code:

# type the following to run the pgm:
# python pgm_name.py inputfile_name

import sys, os, re, string

def parse_file(lines):
    #outfile= open(output_filename, 'w')
    for nextline in lines:
        #print nextline
        mtch= re.search("^ *(Line[0-9]\.+) *([0-9]+)(.+)", nextline)   
        if mtch :
            #print mtch.group(1),',',mtch.group(2),',',mtch.group(3)
            #print mtch.groups()
            if len(mtch.groups()) < 3 :
                  raise 'badly formatted line'
            m1=  mtch.group(1)
            m2=  int(mtch.group(2))
            if str(m2)[0]=='1':
                m2 +=1
            m3=  mtch.group(1)
            if m3 =='ABC':
                m3 = 'DEF'
            print m1,' ',m2,m3
            #outfile.write(m1,' ',m2,m3)    # uncomment here and above to write to a file

#===================================================================
def main():
       
    filename= sys.argv[1]
    try:
        f= open(filename, 'r')

        lines =f.readlines()
    except:
        st ="can't open file" + filename
        raise st
    parse_file(lines)

#---------------------------------------------------------------------------
#----------------------------------------------------------------------------

if __name__ == '__main__':
        main()

#----------------------------------------------------------------------------


jlliagre 08-31-2004 11:28 AM

OK, let's have some fun with shell scripting, another programming language that has regular expressions and that can do maths ;)

Code:

#!/bin/bash
sed 's/ABC/DEF/' ${1:?Missing argument, Usage: $0 file} | while line=$(line)
do
  number=$(expr "$line" : '[^1]*\(11[0-9]*\)DEF')
  prefix=$(expr "$number" : "\(.\{2\}\)")
  [[ "$prefix" = 11 ]] && echo $line | sed 's/'$number'/'$(expr $number + 1)'/' || echo $line
done



All times are GMT -5. The time now is 08:31 PM.