Bash

多行變數在每個換行符之前添加一個製表符

  • November 17, 2019

下面的程式碼片段使用了一個自定義函式 HexNewLine,它基本上轉換了 hexdump 並在字元處中斷 0x0a

$ echo -e "\t{
>   "dependencies": {
>     "prettier": {
>       "version": "1.18.2",
>       "from": "prettier@1.18.2",
>       "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.18.2.tgz"
>     }
>   }
> }" | HexNewLine

00000000   09 7b 0a                                           '.{.'
0000000a   20 20 64 65 70 65 6e 64 65 6e 63 69 65 73 3a 20    '  dependencies: '
0000001a   7b 0a                                              '{.'
0000001c   20 20 20 20 70 72 65 74 74 69 65 72 3a 20 7b 0a    '    prettier: {.'
0000002c   20 20 20 20 20 20 76 65 72 73 69 6f 6e 3a 20 31    '      version: 1'
0000003c   2e 31 38 2e 32 2c 0a                               '.18.2,.'
00000043   20 20 20 20 20 20 66 72 6f 6d 3a 20 70 72 65 74    '      from: pret'
00000053   74 69 65 72 40 31 2e 31 38 2e 32 2c 0a             'tier@1.18.2,.'
00000060   20 20 20 20 20 20 72 65 73 6f 6c 76 65 64 3a 20    '      resolved: '
00000070   68 74 74 70 73 3a 2f 2f 72 65 67 69 73 74 72 79    'https://registry'
00000080   2e 6e 70 6d 6a 73 2e 6f 72 67 2f 70 72 65 74 74    '.npmjs.org/prett'
00000090   69 65 72 2f 2d 2f 70 72 65 74 74 69 65 72 2d 31    'ier/-/prettier-1'
000000a0   2e 31 38 2e 32 2e 74 67 7a 0a                      '.18.2.tgz.'
000000aa   20 20 20 20 7d 0a                                  '    }.'
000000b0   20 20 7d 0a                                        '  }.'
000000b4   7d 0a                                              '}.'
  • 現在我tr用來在換行符後添加一個製表符,但沒有任何反應!
$ echo -e "\t{
>   "dependencies": {
>     "prettier": {
>       "version": "1.18.2",
>       "from": "prettier@1.18.2",
>       "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.18.2.tgz"
>     }
>   }
> }" | tr '\n' '\n\t'
       {
 dependencies: {
   prettier: {
     version: 1.18.2,
     from: prettier@1.18.2,
     resolved: https://registry.npmjs.org/prettier/-/prettier-1.18.2.tgz
   }
 }
}

使用 sed 的解決方案。我使用 bashism$'\t'填充一個變數\t,然後使用這個變數 sed 。

echo -e "{
  "dependencies": {
    "prettier": {
      "version": "1.18.2",
      "from": "prettier@1.18.2",
      "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.18.2.tgz"
    }
  }
}"  | ( TAB=$'\t' ; sed "s/^/$TAB/" )

引用自:https://unix.stackexchange.com/questions/552689