【问题标题】:Create temporary file and edit contents and return the path to the file创建临时文件并编辑内容并返回文件的路径
【发布时间】:2020-06-15 08:49:20
【问题描述】:

我希望使用mktemp 创建一个临时文件,然后在创建后编辑它的内容(使用您喜欢的编辑器;我使用了micro),然后当完成即保存/退出进程时,它应该输出文件的路径到 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 shell unix pipe fish


    【解决方案1】:

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

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

    现在您的管道可以使用mt

    mt | wc
    

    【讨论】:

      【解决方案2】:

      这是bash 解决方案。

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

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

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

      【讨论】:

      • 他说他会接受bash代码,我澄清说是这样。我不认识鱼。
      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 2020-06-22
      • 2011-03-14
      • 2017-04-13
      • 2012-04-11
      • 2022-11-02
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多