Find and Replace characters in IFS file on iSeries(AS400)

Lets say you received a XML, CSV, TXT or any other type of file in the IFS directory and before processing the file and exporting the data to a DB2 database you want to manipulate it. Its very easy with the help of QSHELL sed command, here is how
> echo 'Today is Monday' | sed "s/Mon/Sun/"  
  Today is Sunday                            

In the above example we are taking a string and finding for string "Mon" and replacing it with "Sun". Here is how to do the same thing if we need to do it over a input file say input.txt and output the results in a new file named output.txt
> sed "s/Mon/Sun/" input.txt > output.txt   

What if the same word is there more than one time, the result will be more like this as it only replaces the first instance of the match
> echo "Today is Monday, I hate Monday's" | sed "s/Mon/Sun/"    
  Today is Sunday, I hate Monday's    

Now to fix that you have to use the global replacement /g
> echo "Today is Monday, I hate Monday's" | sed "s/Mon/Sun/g"    
  Today is Sunday, I hate Sunday's                               

How to replace a slash(/) since its used as a separater, You could use the backslash to escape the slash
> echo "Today is Monday/ I hate Monday's" | sed "s/\//,/g" 
  Today is Monday, I hate Monday's                         

In case you are familiar with Java programming then here a program to read a file and replace unwanted characters from an IFS file and create a new file.

public class ModifyIFSData {

 public static void main(String[] args) {

  String fromFileName =  args[0].trim();
  String toFileName =  args[1].trim();

  try {

   FileWriter fWriter = new FileWriter(toFileName.trim());
   BufferedWriter out = new BufferedWriter(fWriter);

   FileInputStream fstream = new FileInputStream(fromFileName.trim());
   DataInputStream in = new DataInputStream(fstream);
   BufferedReader br = new BufferedReader(new InputStreamReader(in));

   String strLine;
   int pos = 0;

   while ((strLine = br.readLine()) != null) {
    pos = strLine.indexOf("â€");
    if(pos > 0){
     strLine = strLine.substring(0,pos)+ strLine.substring(pos+3);
    strLine = strLine.replaceAll("â€", "");
    strLine = strLine.replaceAll("™", "'");
    strLine = strLine.replaceAll("Ø", "-");
    strLine = strLine.replaceAll("abc", "xyz");
  catch (Exception e){


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.