Yesterday I met a problem where I needed to replace the columns of a csv-file separated by whitespace, since this was some pretty basic stuff I wrote a simple program in Java fairly easily.
Today when I woke up I thought that maybe I should try and see how I could do the same with Shell Scripting, so here goes (the programs are available at my github here):
import java.util.Scanner; import java.io.*; public class Cols { /** * This program takes a csv file separated by whitespace and replaces the first with the second column. * @name Cols * @author tcarisland * @date 6.sep.2017 */ public static void main(String args[]) { try { Scanner in = new Scanner(new File(args[0])); PrintWriter out = new PrintWriter(new File(args[1])); while(in.hasNextLine()) { String cols[] = in.nextLine().split("\\s+"); if(cols.length > 1) out.println(cols[1] + " " + cols[0]); } in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
And the Bash program:
#/bin/bash #A minimal version of the cols program to do exactly the same as the java program. #Needs two arguments. rm -f $2 && touch $2; while IFS=" " read c1 c2 do echo $c2" "$c1 >>$2; done < $1