text file

How to use ‘awk’ to print columns from a text file (in any order)

One of my favorite ways to use the Unix awk command is to print columns of information from text files, including printing columns in a different order than they are in in the text file. Here are some examples of how awk works in this use case.

The beginning of a Scala “FileUtils” class

In production code I recommend that you use a good “Files” library like Apache Commons IO, but if you want to create your own Scala FileUtils class, here’s some source code that can help you get started.

First, here’s some code for the FileUtils class (an object, technically):

How to process every line in a file with a Unix/Linux shell script

Unix/Linux shell script FAQ: How do I write a Unix or Linux shell script where I "do something" for every line in a text file?

Solution: An easy way to process every line in a text file is to use a Unix/Linux while loop in combination with the Linux cat command, like this:

How to copy text from the MacOS Terminal to the clipboard

If you ever need to copy text (or a text file) from the MacOS Terminal to the Mac clipboard, I can confirm that the macOS pbcopy command works. It reads from STDIN and copies the text to the clipboard, so commands like these work:

$ echo "foo bar baz" | pbcopy

$ cat /etc/passwd | pbcopy

How to process a CSV file in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.5, “How to process a CSV file in Scala.”

Problem

You want to process the lines in a CSV file, either handling one line at a time or storing them in a two-dimensional array.

Solution

Combine Recipe 12.1, “How to Open and Read a Text File” with Recipe 1.3, “Splitting Strings”. Given a simple CSV file like this named finance.csv:

How to process every character in a text file in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.4, “How to process every character in a text file in Scala.”

Problem

You want to open a text file and process every character in the file.

Solution

If performance isn’t a concern, write your code in a straightforward, obvious way:

How to write text files in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.2, “How to write text files in Scala.”

Problem

You want to write plain text to a file, such as a simple configuration file, text data file, or other plain-text document.

Solution

Scala doesn’t offer any special file writing capability, so fall back and use the Java PrintWriter or FileWriter approaches: