如何从文件中读取,过滤和修改行

时间:2015-05-19 14:06:25

标签: filter io rust

如何在Rust中执行与此D和Java代码类似的操作?

爪哇:

import java.nio.file.*;
import java.io.*;

public class Main {
    public static void main( String[] args ) throws IOException
    {
        Files.lines(Paths.get("/home/kozak/test.txt"))
            .filter(s -> s.endsWith("/bin/bash"))
            .map(s -> s.split(":", 2)[0])
            .forEach(System.out::println);
    }
}

D语言:

import std.algorithm;
import std.stdio;

void main() {
    File("/home/kozak/test.txt")
        .byLine
        .filter!((s)=>s.endsWith("/bin/bash"))
        .map!((s)=>s.splitter(":").front)
        .each!writeln;
}

我尝试了,但我迷失了所有这些所有权的东西

我的锈迹代码:

use std::io::BufReader;
use std::fs::File;
use std::io::BufRead;
use std::io::Lines;

fn main() {
    let file = match File::open("/etc/passwd") {
        Ok(file) => file,
        Err(..)  => panic!("room"),
    };

    let mut reader = BufReader::new(&file);
    for line in reader.lines().filter_map(
        |x| if match x { Ok(v) => v.rmatches("/bin/bash").count() > 0, Err(e) => false}
        { match x { Ok(v2) => Some(v2.split(":").next()), Err(e2) => None }} else
        { None })
    { 
            print!("{}", line.unwrap() );

    }
}

1 个答案:

答案 0 :(得分:7)

你走了:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let f = BufReader::new(File::open("/etc/passwd").unwrap());
    let it = f.lines()
        .map(|line| line.unwrap())
        .filter(|line| line.ends_with("/bin/bash"))
        .map(|line| line.split(":").next().unwrap().to_owned());
    for p in it {
        println!("{}", p);
    }
}

此代码虽然为每个第一个拆分部分分配了一个单独的字符串,但我认为没有流式迭代器就可以避免它。当然,这里的错误处理真的很松散。

我认为一种必要的方法更具惯用性,特别是在错误处理方面:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let f = BufReader::new(File::open("/etc/passwd").unwrap());
    for line in f.lines() {
        match line {
            Ok(line) => if line.ends_with("/bin/bash") {
                if let Some(name) = line.split(":").next() {
                    println!("{}", name);
                } else {
                    println!("Line does not contain ':'");
                }
            },
            Err(e) => panic!("Error reading file: {}", e)
        }
    }
}