Read variable matched by a .* operation

2019-08-28 09:39发布

Modified working solution:

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

Better solution:

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

Broken down:

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.

Please try to keep answers as a working sed line with a description of the replace operation.

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.

I've tried

$1, %1 and 1

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

to no avail.

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 (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

2条回答
beautiful°
2楼-- · 2019-08-28 10:13

I think you want something like this:

$ 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

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 *.

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

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

查看更多
做自己的国王
3楼-- · 2019-08-28 10:20

To use variables as you described, you need \( and \) to group the part you want to reference. So in your case you want to do

sed -e 's/\(\.*\)\[/\1\r\n[/g' testfile.txt

So \1 refers to the part \(\.*\).

查看更多
登录 后发表回答