Search code examples
regexnotepad++

How to add character after a line


I'm trying to perform a few regex steps, and I'd like to add a quotation mark and a comma (",) at the end of these lines without altering any of the rest of the characters in the line.

How would I keep things intact but add the ", after the words: device1, device2, device3 ?

Example of lines I'm working with:

object network device1  
host 192.168.1.11  
object network device2  
host 192.168.1.12  
object network device 3  
host 192.168.1.13  

After my first step of regex, I have modified my first line to include the curly bracket and some formatting with the words "category" and "name" as shown below. However, I don't want to change the word device1, but want to include a quotation and comma after the word device1

{  
"category": "network",  
"name": "device1  
host 192.168.1.11  
{  
"category": "network",  
"name": "device2  
host 192.168.1.11  
{  
"category": "network",  
"name": "device3  
host 192.168.1.13  

I can't figure out how to include the ", with my first step in my regex replace sequence?

I'm using both regexr.com and Notepad++.


Solution

  • You can use this regex to match each entity in your input data:

    object\s+(\w+)\s+([^\r\n]+)[\r\n]+host\s+([\d.]+)
    

    This matches:

    • object\s+ : the word "object" followed by a number of spaces
    • (\w+) : some number of word (alphanumeric plus _) characters, captured in group 1
    • \s+ : a number of spaces
    • ([^\r\n]+) : some number of non-end-of-line characters, captured in group 2
    • [\r\n]+ : some number of end-of-line characters
    • host\s+ : the word "host" followed by a number of spaces
    • ([\d.]+) : some number of digit and period characters, captured in group 3

    This can then be replaced by:

    {\n "category": "$1",\n "name": "$2",\n "host": "$3"\n},
    

    To give output (for your sample data) of:

    {
     "category": "network",
     "name": "device1",
     "host": "192.168.1.11"
    },
    {
     "category": "network",
     "name": "device2",
     "host": "192.168.1.12"
    },
    {
     "category": "network",
     "name": "device 3",
     "host": "192.168.1.13"
    },
    

    Regex demo on regex101

    Now you can simply add [ at the beginning of the file and replace the last , with a ] to make a valid JSON file.