繁体   English   中英

如何使用fish添加文件

[英]How to prepend a file using fish

我看到bash甚至zsh有几个很好的答案(即Here )。 虽然我没能找到一个好的fish

是否有规范的或干净的将字符串或几行添加到现有文件(就地)中? 类似于cat "new text" >> test.txt对 append 所做的事情。

作为 fish 旨在简化的有意目标的一部分,它避免了 zsh 中的语法糖。 等同于 zsh-only 代码<<< "to be prepended" < text.txt | sponge text.txt 鱼中的<<< "to be prepended" < text.txt | sponge text.txt是:

begin; echo "to be prepended"; cat test.txt; end | sponge test.txt

sponge是来自moreutils package的工具; fish 版本和 zsh 原版一样需要它。 但是,您可以轻松地将其替换为 function; 考虑以下:

# note that this requires GNU chmod, though it works if you have it installed under a
# different name (f/e, installing "coreutils" on MacOS with nixpkgs, macports, etc),
# it tries to figure that out.
function copy_file_permissions -a srcfile destfile
  if command -v coreutils &>/dev/null  # works with Nixpkgs-installed coreutils on Mac
    coreutils --coreutils-prog=chmod --reference=$srcfile -- $destfile
  else if command -v gchmod &>/dev/null  # works w/ Homebrew coreutils on Mac
    gchmod --reference=$srcfile -- $destfile
  else
    # hope that just "chmod" is the GNU version, or --reference won't work
    chmod --reference=$srcfile -- $destfile
  end
end

function mysponge -a destname
  set tempfile (mktemp -t $destname.XXXXXX)
  if test -e $destname
    copy_file_permissions $destname $tempfile
  end
  cat >$tempfile
  mv -- $tempfile $destname
end

function prependString -a stringToPrepend outputName
  begin
    echo $stringToPrepend
    cat -- $outputName
  end | mysponge $outputName
end

prependString "First Line" out.txt
prependString "No I'm First" out.txt

对于文件大小为中小型(适合内存)的特定情况,请考虑使用ed程序,该程序将通过将所有数据加载到 memory 中来避免临时文件。 例如,使用以下脚本。 这种方法避免了安装额外包(moreutils 等)的需要。

#! /usr/env fish
function prepend
  set t $argv[1]
  set f $argv[2]
  echo '0a\n$t\n.\nwq\n' | ed $f
end

暂无
暂无

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

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