linedance
Read lines from either stdin or filenames provided on the CLI.
This functionality is similar to the
fileinput module in Python.
Usage
There is an example file in the example directory that shows
how you would use this in your own project. This is the example
code:
// examples/simple_usage.rs
use input;
Let's build this example first so that we can run it directly.
(It gets cumbersome to test stdin and CLI parameters with cargo run.)
The binary simple_usage is located in the target/debug/examples directory. There is also a text file in the example directory that you can use to test the program, called data.txt.
First we'll show how to use stdin as the input source:
|
Now we'll show how to use a file as the input source:
The output will be the same as the previous example.
When used with the --files flag, the program will read the lines from all the files provided on the CLI. This allows it to be used with shell wildcards.
How to use with Clap
linedance is designed to be used without any special libraries for argument parsing because it is a simple utility. However, it can be used with clap if you want to use it with a more complex CLI application.
To use it with clap, or any similar library, the basic idea is to just ignore the --files CLI parameter in your code. Leave that to linedance to handle. Here is an example of how you can do that:
-
First, add both
linedanceandclapto yourCargo.toml:[] = "0.1.0" = { = "4.5", = ["derive"] } -
In your
main.rs, use clap to define your CLI structure, but leave the file handling to linedance:use Parser; use input; -
When running your application, use the
--filesflag provided by linedance to specify input files:Or use stdin:
|