Hacker News new | ask | show | jobs
by test9753 3044 days ago
In Ocaml [LOC: 24] [Level: Beginner]

  open Core

  let () =
    if Array.length Sys.argv <> 5 then
      Printf.eprintf "Invalid args\nUsage: %s <input.csv> <column-name> <replacement-string> <output.csv>" Sys.argv.(0)
    else
      let input_file, column_name, replacement, output_file = Sys.argv.(1), Sys.argv.(2),Sys.argv.(3),Sys.argv.(4) in 
      In_channel.with_file input_file ~f:(fun in_ch ->
      match In_channel.input_line in_ch with 
      | None -> Printf.eprintf "Cannot read first line"
      | Some first_line ->
        let columns = String.split first_line ~on:',' in 
        match List.findi columns ~f:(fun _ col -> col = column_name) with 
        | None -> Printf.eprintf "Cannot find column: %s" column_name
        | Some (index, _) ->
          let _ = Out_channel.with_file output_file ~f:(fun out_ch ->
            Out_channel.output_string out_ch (first_line ^ "\n");
            In_channel.fold_lines in_ch ~init:() ~f:(fun _ line ->
              let in_columns = String.split line ~on:',' in 
              let out_columns = List.mapi ~f:(fun i col -> if i = index then replacement else col) in_columns in 
              let out_line = (String.concat ~sep:"," out_columns) ^ "\n" in
              Out_channel.output_string out_ch out_line
            )
          ) in ())