简体   繁体   English

创建具有特定扩展名的临时文件并在VS Code中打开

[英]Create temporary file with specific extension and open it in VS Code

I'm trying to pipe some output on bash stdout into a new temporary file and open this file using VS Code. 我正在尝试将bash stdout上的一些输出传递到新的临时文件中,并使用VS Code打开此文件。

The file content might not always be plain text but also could be yaml and I want to create the temp file with yaml extension so VS Code uses the correct language mode. 文件内容可能并不总是纯文本,也可能是yaml ,我想创建带有yaml扩展名的临时文件,因此VS Code使用正确的语言模式。

I tried this but I end up with a file having the txt in VS Code. 我尝试了这个,但最终得到了一个在VS Code中具有txt的文件。

cat yaml > $(mktemp $TMPDIR$(uuidgen).yaml) | code -

cat yaml is just an example for a command which might write yaml content to stdout . cat yaml只是命令的一个示例,该命令可能会将yaml内容写入stdout

mktemp --suffix=.yaml would be the way to go but this isn't supported on macOS. mktemp --suffix=.yamlmktemp --suffix=.yaml的方法,但macOS不支持。

I found a solution: 我找到了解决方案:

temp=$(mktemp $TMPDIR.XXXXXXXXXXXX.$(uuidgen).yaml) && ls -la > $temp && code $temp

Of course there might be better ones and I'm looking forward to it. 当然,可能会有更好的选择,我很期待。

You can do it this way: 您可以这样操作:

TMPDIR='/tmp' # Give a value to TMPDIR for the purpose of this answer
mktemp "${TMPDIR}/XXXXXXXXXXXX_$(uuidgen).yaml" |
  xargs -n 1 -I {} -- \
    code --file-uri "file://{}"
  • mktemp "${TMPDIR}/XXXXXXXXXXXX_$(uuidgen).yaml" : mktemp "${TMPDIR}/XXXXXXXXXXXX_$(uuidgen).yaml"
    Create the temporary file into $TMPDIR with name composed of: 将临时文件创建到$TMPDIR ,其名称包括:
    • 12 random alphanumeric mixed case letters 12个随机字母数字混合大小写字母
      replacing the upper_case X , 替换大写的X
    • followed by underscore _ , 下划线_
    • followed by a random UUID generated by the uuidgen command, 然后是uuidgen命令生成的随机UUID,
    • and suffixed by the .yaml extension. 并以.yaml扩展名结尾。
  • | xargs -n 1 -I {} | xargs -n 1 -I {} : | xargs -n 1 -I {}
    Pass the newly created temporary file name to xargs , which will convert it into an argument: 将新创建的临时文件名传递给xargs ,它将把它转换为参数:
    • -n 1 : One argument for each command -n 1 :每个命令一个参数
    • -I {} : Replace placeholder string {} with the argument -I {} :用参数替换占位符字符串{}
    • -- : End of the xargs options. --xargs选项的结尾。
  • code --file-uri "file://{}" : code --file-uri "file://{}"
    code is invoked by xargs . codexargs调用。
    • --file-uri <uri> Opens a window with given file uri(s) --file-uri <uri>使用给定的文件uri打开一个窗口
    • "file://{}" : The uri for the temporary file just created. "file://{}" :刚刚创建的临时文件的uri。
      xargs will replace {} by the temporary file path. xargs将用临时文件路径替换{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM