skip to Main Content

In the process of converting a blog from WordPress to Hugo, I find that I need to do a global search and replace for tags to convert them to a list of strings.

Currently I have something like this:

tags: owl, owl2, rdfs, rdf, snippets, vscode, visual studio code

But I need something like this:

tags: ["owl", "owl2", "rdfs", "rdf", "snippets", "vscode", "visual studio code"]

I have a variety of editors such as VSCode, VS22, Neovim, Rider etc. at my disposal as well as sed, gawk etc, so any solution will do.

2

Answers


  1. To find all these with such a pattern: ^(tags: )|(, )|$.

    Then the expected result for a given string can be achieved in 3 steps using VSCode:

    1. Search for a string tags: (note there is a space) using command+F/cntrl+F and to a Replace field add a string tags: [".
    2. Search for , (note there is a space) and replace it with ", ".
    3. Depending on what’s at the end of the line search for $ or n (in a search dialog select Use Regular Expression option) and replace it with "].
    Login or Signup to reply.
  2. I would harness GNU sed for this task following way, let file.txt content be

    tags: owl, owl2, rdfs, rdf, snippets, vscode, visual studio code
    

    then

    sed -e 's/ /["/' -e 's/$/"]/' -e 's/, /", "/g' file.txt
    

    gives output

    tags:["owl", "owl2", "rdfs", "rdf", "snippets", "vscode", "visual studio code"]
    

    Explanation: I give three instructions

    • replace space using [" once (i.e. it will affect only first space)
    • replace end of line using "] (i.e. append "])
    • replace , using ", " globally (i.e. it wil affect all , )

    (tested in GNU sed 4.7)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search