2018年8月23日 星期四

[Linux 常見問題] How to extract a value from a string using regex and a shell?

Source From Here 
Question 
I am in shell and I have this string: 
12 BBQ ,45 rofl, 89 lol

Using the regexp: \d+ (?=rofl), I want 45 as a result. Is it correct to use regex to extract data from a string? The best I have done is to highlight the value in some of the online regex editor. Most of the time it remove the value from my string. 

I am investigating expr, but all I get is syntax errors. How can I manage to extract 45 in a shell script? 

How-To 
You can do this with GNU grep's perl mode: 
// -P, --perl-regexp: Interpret PATTERN as a Perl regular expression. 
// -o, --only-matching: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
 
# echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...