網站首頁 編程語言 正文
一、功能:
1、輸入要查詢的字符串
和文件名
,輸出所有匹配的行的內容
2、如果設置環境變量IGNORE_CASE
,則grep匹配將忽略大小寫
3、可使用 >
符號來重定向標準輸出到指定文件中
二、介紹
2.1 使用到的知識:
- 讀取命令行參數
- 讀取文件內容
- 錯誤處理
- Test Driven Development(TDD)
- 使用環境變量控制不同行為
2.2 代碼
1、main.rs
use std::env; use std::process; use minigrep::Config; fn main() { // let args: Vec<String> = env::args().collect(); // let query = &args[1]; // let filename = &args[2]; // let content = fs::read_to_string(filename).expect("You have a problem in read a file"); // println!("Filename: {}", filename); // println!("File content:\n{}", content); //refactoring after let args: Vec<String> = env::args().collect(); // let config = Config::new(&args); let config = Config::new(&args).unwrap_or_else(|err| { eprintln!("Problem parse arguments: {}", err); process::exit(1); }); println!("query: {}, filename: {}", config.query, config.filename); if let Err(e) = minigrep::run(config) { eprintln!("Application Error: {}", e); process::exit(1); } }
2、lib.rs
use std::error::Error; use std::fs; use std::env; pub struct Config { pub query: String, pub filename: String, pub ignore_case: bool, } impl Config { // fn new(args: &[String]) -> Config { // let query = args[1].clone(); // let filename = args[2].clone(); // Config {query, filename} // } pub fn new(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("No enough arguments"); } let query = args[1].clone(); let filename = args[2].clone(); let ignore_case = env::var("IGNORE_CASE").is_ok(); Ok(Config{query, filename, ignore_case}) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let content = fs::read_to_string(config.filename)?; // println!("With text:\n{}", content); let result = if config.ignore_case { search_case_insensitive(&config.query, &content) } else { search(&config.query, &content) }; for line in result { println!("{}", line); } Ok(()) } pub fn search<'a>(query: &str, content: &'a str) -> Vec<&'a str> { let mut result = Vec::new(); for line in content.lines() { if line.contains(query) { result.push(line); } } result } pub fn search_case_insensitive<'a>(query: &str, content: &'a str) -> Vec<&'a str> { let mut result = Vec::new(); let query = query.to_lowercase(); for line in content.lines() { if line.to_lowercase().contains(&query) { result.push(line); } } result } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "xwp"; let content = "\ Hello,rust! xwp is handsome You know!"; assert_eq!(vec!["xwp is handsome"], search(query, content)); } #[test] fn case_insensitive() { let query = "xWp"; let content = "\ Hello,rust! xwp is handsome You KonW"; assert_eq!(vec!["xwp is handsome"], search_case_insensitive(query, content)); } }
三、使用
- 需要輸入兩個參數,第一個是query,第二個是filename,如果參數少于兩個會報錯。
- 如:
cargo run xwp xwphs.txt
,xwp是要查詢的內容,xwphs.txt是文件。 -
minigrep默認是大小寫敏感的,可通過設置
IGNORE_CASE
環境變量,使得查詢忽略大小寫。
在powershell中設置臨時環境變量如:$Env:IGNORE_CASE=1
,解除:Remove-Item Env:IGNORE_CASE
;在shell中直接:將IGNORE_CASE=1放在最開始
參數不足時,提示Problem parse arguments: No enough argumentss
設置環境變量后,不區分大小寫,查詢到了信息
原文鏈接:https://blog.csdn.net/qq_46480020/article/details/125964847
相關推薦
- 2022-04-12 React工作流程及Error?Boundaries實現過程講解_React
- 2022-05-01 淺談Redis哨兵模式高可用解決方案_Redis
- 2022-10-07 android?studio后臺服務使用詳解_Android
- 2022-06-12 IDEA如何配置Tomcat
- 2023-07-28 select 框添加樹結構(todu)
- 2022-08-25 Python并行編程多線程鎖機制Lock與RLock實現線程同步_python
- 2022-07-12 快速上手Vim編輯器
- 2022-09-09 C#正則表達式與HashTable詳解_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支