skip to Main Content

I have a file with lines of text that looks like this:

category1.name1
name2

I want the output to look like this:

category1   name1
            name2

I’m editing this file in VS Code on a Mac. I’m happy to use regex in VS Code, or a command line solution.
I can replace the "." with a tab easily enough, but how do I add tabs to the start of the line if there is no "." in the line?

2

Answers


  1. Here’s a command-line solution using awk:

    cat <filename> | awk '{ gsub(/./, " ");  printf "%-15s%sn", NF == 1 ? " " : $1, $NF }'
    

    You can adjust the width of the first field (the %-15s in the printf) to something more appropriate as necessary, but otherwise, this seems to fill in what you’re looking for.

    For example:

    % printf "category1.name1nname2" | awk '{ gsub(/./, " ");  printf "%-15s%sn", NF == 1 ? " " : $1, $NF }'
    category1      name1
                   name2
    

    If your heart’s set on using tabs, you can use the following modified version, but if the first field is longer than a tab character’s width (e.g., eight), things won’t line up:

    cat <filename> | awk '{ gsub(/./, " ");  printf "%st%sn", NF == 1 ? "t" : $1, $NF }'
    
    Login or Signup to reply.
  2. Here is another way to do this. I am not sure how uniform your data is try this.

    Using an extension I wrote, Find and Transform, you can use javascript in a keybinding to get the lengths of the words you need. Demo:

    pad the middle of a word and align next line demo

    That uses this keybinding:

    {
      "key": "alt+y",
      "command": "findInCurrentFile",
      "args": {
        "find": "(^.+?)\.(.*)n(^[^\.n]+$)",
        "replace": [
          "$${",
            "const len1 = '$1'.length;",  // group 1 length
            "const space = 4;",           // how many spaces to put inside first line
            "const len3 = '$3'.length;",  // group 3 length
    
            "return '$1'.padEnd(len1 + space, ' ') + '$2' + `n` + '$3'.padStart(len3  +len1 + space, ' ');",
    
            "return str;",
          "}$$",
        ],
        "isRegex": true,
        // "restrictFind": "selections"  // use this if you want to limit to selections
        "postCommands": "cancelSelection",
      }
    },
    

    This uses spaces to align the lines, much easier than tabs. If it is absolutely necessary to use tabs let me know and I’ll see if anything can be done to change this.

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