创建临时文件并编辑内容和 return 文件路径

Create temporary file and edit contents and return the path to the file

我希望使用 mktemp 创建一个临时文件,然后在创建后编辑它的内容(使用您喜欢的编辑器;我使用 micro),然后在完成后即 saved/exited处理它应该将文件路径输出到 stdout/pipe/replace 作为参数。

除了打印创建和使用的文件的路径外,我什么都能做。我不想依赖编辑器在关闭时输出路径的能力,因此可以使用任何编辑器。

我在尝试什么。

# creates a file. passes it's path to editor to open it. 
# then we can make changes and save. finally quit.
> micro (mktemp)

但是输出什么都没有,我希望它是传入的原始路径。 我该怎么做?

这些是示例用例,它们不起作用,因为我无法在保存后输出路径。

# e.g. a full test case; create tmp file, fill it, read it, find it...
> micro (mktemp) | cat | grep 'find me*!'

# or you want to count the words
> micro (mktemp) | tail | wc 

# another way it should work as well! i.e. pros-sub
> cat (micro (mktemp)) | sed 's/red/green/g'

# bonus points (I mean it, 50 extra karma). You might need to restructure the chain
# i.e. ->create tmp, fill it, save it, read it, manipulate it, save it 
# back to disk (append/replace)
> cat (micro (mktemp)) | sed ' s/red/green/g' >> <original_file_path>

我在 fish 工作,因为我很乐观,正在寻找解决方案。但是,如果您已经在 bash 中知道它,那么很想看到它并且会很有用。所以我会标记两者

这是一个 bash 解决方案。

将路径名放入变量中,以便稍后在脚本中重用它。

要获取命令的输出,您可以使用 $(command),而不仅仅是 (command)

temp=$(mktemp)
micro "$temp"
wc < "$temp"

在鱼shell中,你可以定义一个函数,这里mt:

function mt
  set -l path (mktemp)
  micro $path </dev/tty >/dev/tty
  cat $path
 end

现在您的管道可以使用 mt:

mt | wc