The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Dummies Questions & Answers
Google UNIX.COM



View Single Post in UNIX Forums - Click on the Thread or Permalink to View Entire Thread -->
  #11 (permalink)  
Old 10-23-2006
ghostdog74 ghostdog74 is offline
Registered User
 

Join Date: Sep 2006
Posts: 1,434
Quote:
Originally Posted by ghostdog74
Python alternative

Code:
#!/usr/bin/python
1.import fileinput
2.for lines in fileinput.FileInput("input.txt", inplace=1): #inplace edit
3. 	a = lines.strip().split(",")
4. 	if a[0] == "asd":
5. 		insertstring = ",33,44," 
6. 	if a[0] == "mnmn":
7. 		insertstring = ",55,66," 
8. 	print a[0] , insertstring , ','.join(a[1:])
1. fileinput is a Python standard module for looping over files and processing them. So we import it into the script.
2. Here we loop over the lines in the file, using for loop. The "inplace = 1" argument says to perform modification to the file "without creating a temporary file", ie inplace editing.
3. Strip the line of newlines and then split them up using ',' as delimiter. Eg asd,12,12,12,12,1,2,1,1,1,1,1 will become ['asd', '12', '12', '12', '12', '1', '2', '1', '1', '1', '1', '1']. In Python , strings are immutable, do i use a list
4-7. to refer to elements of a list in Python, we use indexes. eg a[0] refers to the first element, which is "asd". The second element will be a[1] which is '12' and so on.
8. a[1:] means get from index 1 (element 2) till the end of the list.
",".join ( a[1:] ) means to join ['12', '12', '12', '12', '1', '2', '1', '1', '1', '1', '1'] back to a string 12,12,12,12,1,2,1,1,1,1,1 , using commas as delimiters.
Reply With Quote