在linux脚本中,我想用文件中的数据分配几个变量。
该命令应该能够:
我正在搜索像
这样的命令mydate=`regextractor "^date:\s*(\S{10}).*$" myfile.md`
mytitle=`regextractor "^title:\s*(.*)\s*$" myfile.md`
echo $mydate - $mytitle
我的档案:
---
slug: article1
date: 2012-01-29 15:34:01
title: What is the best monetary system invented til now?
author: raisercostin<raisercostin@gmail.com>
tags: currency,monetary,system
type: question
toslug: article
此处测试了正则表达式:https://regex101.com/r/y311eP/1
grep -o "toslug:\(.*\)" myfile.md
=&gt; toslug: article
grep --color=no -oE "toslug:(.*)" myfile.md
=&gt; toslug: article
sed -nE "s/^date:\s*(\S*)//p" myfile.md
更新:它实际上支持捕获组,但您需要启用--regexp-extended with -E parameter awk '/^date:\s*(.*)$/' myfile.md
Linux vagrant-ubuntu-trusty-64 3.13.0-101-generic #148-Ubuntu SMP Thu Oct 20 22:08:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
上:
sed -nE 's/^date:\s*(\S*)/\1/p' myfile.md
=&gt; 2012-01-29 15:34:01
sed -nE 's/^date:\s*(\S{10})/\1/p' myfile.md
=&gt; 2012-01-29 15:34:01
sed -nE 's/^date:\s*(\S*)$/\1/p' myfile.md
=&gt;没有线awk '{ match($0, /^date:\s*(\S{10}).*$/, a); if(a[1])print a[1]}' myfile.md
=&gt; 2012-01-29
Darwin costins-MBP.router1 16.3.0 Darwin Kernel Version 16.3.0: Thu Nov 17 20:23:58 PST 2016; root:xnu-3789.31.2~1/RELEASE_X86_64 x86_64
上:
sed -nE 's/^date:\s*(\S*)/\1/p' myfile.md
=&gt; 2012-01-29 15:34:01
- 不消耗初始空格sed -nE 's/^date:\s*(\S{10})/\1/p' myfile.md
=&gt;没有线sed -nE 's/^date:\s*(\S*)$/\1/p' myfile.md
=&gt;没有线awk '{ match($0, /^date:\s*(\S{10}).*$/, a); if(a[1])print a[1]}' myfile.md
=&gt; awk: syntax error at source line 1{ match($0, >>> /^date:\s*(\S{10}).*$/, <<<
答案 0 :(得分:1)
这是一个perl oneliner:
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
<强>输出:强>
perl -E 'undef$/;$_=<>;($d,$t)= $_ =~ /\ndate:\s*(\S{10}).+\ntitle:\s*(.+?)\R/s;say "$d - $t";' <file.txt
file.txt的
2012-01-29 - What is the best monetary system invented til now?
答案 1 :(得分:1)
(gnu)awk支持捕获:
awk '/^date/ { match($0, /^date:[[:blank:]]*([^[:blank:]]{10}).*$/, a); print a[1]}' myfile.md
给出:2012-01-29
awk '/title/ { match($0, /^title:[[:blank:]]*([^[:blank:]]*.*$)/, a); print a[1]}' myfile.md
给出:What is the best monetary system invented til now?
答案 2 :(得分:0)
基于Jan Smydke的回应。这匹配两组。
<强>输入:强>
regextractor () {
perl -E 'undef$/;$_=<>;($v1,$v2)= $_ =~ /'$1'/m;say "$v1$v2";' <$2
}
regextractor "^date:\s*(\S{10}).*$" myfile.md
regextractor "^title:\s*(.*)\s*$" myfile.md
<强>输出:强>
2012-01-29
What is the best monetary system invented til now?