读取由 .* 操作匹配的变量 [英] Read variable matched by a .* operation

查看:39
本文介绍了读取由 .* 操作匹配的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改后的工作解决方案:

Modified working solution:

sed -r "s/(\.*)\[/\1\r[/g"

更好的解决方案:

sed -r "s/(.*)\[/\1\r[/g"

分解:

s/
(\.*)\[    -String to Capture followed by [
/
\1\r[      -Line to replace with
/g" 

I believe for subsequent strings, more of these are made
(\.*) but in the same order they appear from left to right, the variables are referenced.

请尽量将答案保留为带有替换操作说明的有效 sed 行.

我确实想学习如何在 sed 中使用变量.因此,如果您有其他解决方案,我完全没听错,但我确实希望学习如何在 sed 中操作变量.

I actually do want to learn how to use variables in sed. So if you have another solution, I'm all ears, but I really do wish to learn how to manipulate variables in sed.

我试过了

$1、%1 和 1

作为这些的组合\$1,\%1 \1和/$1/%1/1

as a combination of these \$1, \%1 \1 and /$1 /%1 /1

无济于事.

这是我用空白部分替换匹配部分的起始工作脚本.

Here's my starting working script that replaces the matching section with a blank section.

sed -e "s/\.*\[//g" testfile.txt

我想对脚本做的是替换(* 代表任何先前的(非空白)字符串)

What I want to do with the script is replace (* representing any prior (nonwhitespace) string)

*[ 

with(中间没有空行或制表符)

with (no blank lines or tabs in-between either)

*
[

所以我想到了类似的东西

So I figured something like

C:\temp>sed -e "s/\.*\[/\1/g" testfile.txt
sed: -e expression #1, char 12: invalid reference \1 on `s' command's RHS

推荐答案

我想你想要这样的:

$ cat file.txt 
this should be the first line*[and this should be the second
$ sed -r 's/([^*]*\*)/\1\n/' file.txt 
this should be the first line*
[and this should be the second

请注意,使用 -r 选项意味着您不需要转义括号.如果不使用 -r,则必须将 ( 替换为 \()\)第一个捕获组在第一个括号内

Note that using the -r option means you don't need to escape the parens. If you don't use -r you must replace ( with \( and ) with \) The first capture group is within the first parens

([^*]*\*)

捕获第一个 * 之前(并包括)的所有内容.

which captures everything before (and including) the first *.

替换 (\1\n) 打印第一个捕获组,然后是换行符,然后是该行的其余部分.

The replacement (\1\n) prints the first capture group, followed by a newline, followed by the rest of the line.

如果您真的对学习 sed 感兴趣,请查看 本教程

And if you're really interested in learning sed, check out this tutorial

这篇关于读取由 .* 操作匹配的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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