octosquidopus
octosquidopus

Reputation: 3713

sed: change word order and replace

I'm trying to replace;

randomtext{{XX icon}}

by

randomtext{{ref-XX}}

..in a file, where XX could be any sequence of 2 or 3 lowercase letters.


I attempted rearranging the word order with awk before replacing "icon" with "ref-" with sed;

awk '{print $2, $1}'

..but since there is no space before the first word nor after the second one, it messed up the curly brackets;

icon}} {{XX

What is the simplest way to achieve this using sed?

Upvotes: 1

Views: 1882

Answers (2)

Thor
Thor

Reputation: 47099

Here's a more generic version using hash tags (#) as regex delimiter:

sed 's#{{\([^ ]*\) [^}]*#{{ref-\1#'
  • {{ anchors the regex at the double open curly braces.
  • \([^ ]*\) captures everything up until a space.
  • [^}]* eats everything up until a closing curly brace.

Upvotes: 1

perreal
perreal

Reputation: 97938

 sed 's/{{\([a-z]\{2,3\}\)\sicon/{{ref-\1/'

This one liner uses the substitute command s/PATTERN/REPLACE/. {{ matches two brackets. \([a-z]\{2,3\}\) captures the pattern that matches 2 or 3 lowercase letters. \s matches a white space. icon matches the literal string "icon". Then we replace the match, that is, {{....icon with the literal string {{ref- and the captured 2 or 3 letter word.

Upvotes: 2

Related Questions