Filter 如何从文件中读取、筛选和修改行

Filter 如何从文件中读取、筛选和修改行,filter,io,rust,Filter,Io,Rust,如何在Rust中执行类似于此D和Java代码的操作 爪哇: 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!wr

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

爪哇:

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() );

    }
}
给你:

使用std::fs::File;
使用std::io::{BufRead,BufReader};
fn main(){
让f=BufReader::new(File::open(“/etc/passwd”).unwrap();
让它=f.行()
.map(| line | line.unwrap())
.filter(| line | line.end_以(“/bin/bash”))
.map(| line | line.split(“:”).next().unwrap().to|u owned());
对于其中的p{
println!(“{}”,p);
}
}
虽然这段代码为每个第一个拆分的部分分配了一个单独的字符串,但我认为如果没有流迭代器,就不可能避免它。当然,这里的错误处理非常松散

我想命令式方法更惯用,尤其是在错误处理方面:

使用std::fs::File;
使用std::io::{BufRead,BufReader};
fn main(){
让f=BufReader::new(File::open(“/etc/passwd”).unwrap();
对于f中的行。行(){
火线{
Ok(line)=>如果line.以(“/bin/bash”)结尾{
如果让Some(name)=line.split(“:”).next(){
println!(“{}”,名称);
}否则{
println!(“行不包含“:”);
}
},
Err(e)=>panic!(“读取文件时出错:{}”,e)
}
}
}

到目前为止您做了什么?你应该有足够的经验来理解,SO不是一个你把你的作品“请为我做”放到其他人身上的网站。我的错,我点击帖子太早了,没有意识到它错过了我的尝试。非常感谢。你觉得这个解决方案怎么样:@Kozzi11,看起来不错。不过格式设置有点不合适,如果你坚持使用迭代器,你最好使用一些方便的迭代器适配器,比如
foreach()
,这样你就不需要粗暴地强迫迭代器使用
last()
或其他什么工具运行。@Vladimitavevevev我的格式设置是非正统的,是的:)谢谢你提到itertools,我不知道。。。
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() );

    }
}