Skip to content

Instantly share code, notes, and snippets.

@kossoy
Created May 18, 2012 05:49
Show Gist options
  • Save kossoy/2723432 to your computer and use it in GitHub Desktop.
Save kossoy/2723432 to your computer and use it in GitHub Desktop.
Get second column from files in directory and write to csv
#!/usr/bin/env bash
FOLDER=name_of_folder
for f in $(ls $FOLDER)
do
echo "Processing $f"
awk '{print $2}' $FOLDER/$f | sed "s/(//" | sed "s/)//" > $FOLDER/$f.csv
done
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ListFiles {
public static void main(String[] args) throws IOException {
String path = (args.length > 0) ? args[0] : ".";
String filePath;
String[] fileContent;
String[] lines;
String outFileContent = "";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
filePath = path + "/" + listOfFile.getName();
if (filePath.endsWith(".txt") || filePath.endsWith(".TXT")) {
fileContent = readLines(filePath);
System.out.println("Processing: " + filePath);
for (String line : fileContent) {
lines = line.split(" ");
if (lines.length > 0) {
outFileContent += lines[1].replace("(", "").replace(")", "") + "\n";
}
}
writeLines(filePath + ".csv", outFileContent);
}
}
}
} else {
System.out.println("No such folder");
}
System.out.println("Done");
}
private static String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
private static void writeLines(String filename, String content) {
try {
File f;
f = new File(filename);
if (!f.exists()) {
f.createNewFile();
}
FileWriter fStream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fStream);
out.write(content);
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment