如何为 sed 创建一个简单的正则表达式? [英] How can I create a simple regexp for sed?

查看:49
本文介绍了如何为 sed 创建一个简单的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我得到的第 1 个文本文件:

Here's a text file #1 I've got:

abc:
  xyz: Hi StackOverflow!
  x-cool-value: v5

这是另一个:

abc:
  xyz: Hi StackOverflow!
  x-cool-value: foobar/v7

所以对于第一个文件,我想提取 v5 和 #2:v7.x-cool-value 始终是一个常量/存在于输入文本文件中.

so for the first file I'd like to extract v5 and for #2: v7. x-cool-value is always a constant / present in the input text files.

我想出了:

$ sed -n 's/^ *x-cool-value: *//p' foo.yaml
# return either `v2` or `foobar/v7`

但不确定如何使其适用于两个测试文件.

but not sure how to make it work for both test files.

推荐答案

好吧,那肯定行不通.通过添加 : * 你只是在说一个冒号后跟零个或多个空格".如果您想要的是空格后的整行,那效果很好.但是如果你想跳过的不仅仅是空格,你必须让你的正则表达式匹配你想跳过的内容.

Well, sure that won't work. By adding : * you're just saying "a colon followed by zero or more spaces". That works fine if what you want is the entire line after the spaces. But if you want to skip more than spaces you have to make your regular expression match the stuff you want to skip.

看起来,虽然你没有真正定义它,但你想跳过所有空格 PLUS 直到并包括最后一个 / 的所有字符,如果存在的话.另一种解释你想要什么的方法是,所有字符直到并包括 first / 但因为你没有说我选择实现前者.

It seems, although you didn't actually define it, that you want to skip all spaces PLUS all characters up to and including a final /, if one exists. Another way to interpret what you want is, all characters up to and including the first / but since you didn't say I chose to implement the former.

可以这样做:

sed -n 's,^ *x-cool-value: *\(.*/\)*,,p' foo.yaml

我在这里将正则表达式分隔符从 / 更改为 , 但您可以选择任何您喜欢的内容:我不想使用 / 因为它出现在正则表达式中.

I changed the regular expression delimiter from / to , here but you can choose whatever you like: I didn't want to use / since that appears in the regular expression.

额外的位 \(.*/\)* 表示匹配一组以 / 结尾的字符,零次或多次.

The extra bit \(.*/\)* means, match a group of characters that ends with a /, zero or more times.

建议您去找一本书或网站,为您提供有关正则表达式的一些说明.它们非常有用,对于任何想要在 Linux 和 MacOS 等 POSIX 系统中执行任何类型的非平凡脚本的人来说都是绝对必要的.

You would be well-advised to go find a book or a website that gives you some instruction on regular expressions. They're extremely useful and an absolute requirement for anyone wanting to do any sort of non-trivial scripting in POSIX systems like Linux and MacOS.

这篇关于如何为 sed 创建一个简单的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆