> 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.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; 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"); out.write(strLine); } in.close(); out.close(); } catch (Exception e){ e.printStackTrace(); } } }
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.