简体   繁体   中英

Replace "advanced" pattern in sed

I cant figure out how to change this:

\usepackage{scrpage2}
\usepackage{pgf} \usepackage[latin1]{inputenc}\usepackage{times}\usepackage[T1]{fontenc}
\usepackage[colorlinks,citecolor=black,filecolor=black,linkcolor=black,urlcolor=black]{hyperref}

to this using sed only

REPLACED
REPLACED REPLACEDREPLACEDREPLACED
REPLACED

Im trying stuff like sed 's.\\.*\([?*]\)\.{ \+} REPLACED g' FILE

but that gives me

REPLACED
REPLACED
REPLACED

I think.* gets used and everything else in my pattern is just ignored, but I can't figure out how to go about this.

After I learned how to format a regex like that, my next step would be to change it to this:

\usepackage{scrpage2}
\usepackage{pgf} 
\usepackage[latin1]{inputenc}
\usepackage{times}
\usepackage[T1]{fontenc}
\usepackage[colorlinks,citecolor=black,filecolor=black,linkcolor=black,urlcolor=black]{hyperref}

So I would appreciate any pointers in that direction too.

Here's some code that happens to work for the example you gave:

sed 's/\\[^\\[:space:]]\+/REPLACED/g'

Ie match a backslash followed by one or more characters that are not whitespace or another backslash.

To make things more specific, you can use

sed 's/\\[[:alnum:]]\+\(\[[^][]*\]\)\?{[^{}]*}/REPLACED/g'

Ie match a backslash followed by one or more alphanumeric characters, followed by an optional [ ] group, followed by a { } group.

The [ ] group matches [ , followed by zero or more non-bracket characters, followed by ] .

The { } group matches { , followed by zero or more non-brace characters, followed by } .

Perl to the rescue: It features the "frugal quantifiers"

perl -pe 's!\\.*?\.?{.+?}!REPLACED!g' FILE

Note that I removed the capturing group as you didn't use it anywhere. Also, [.*] matches either a dot or an asterisk, but you probably wanted to match a literal dot instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM