【问题标题】:how i can delete something from file?我怎样才能从文件中删除一些东西?
【发布时间】:2010-09-21 13:20:44
【问题描述】:

我想从文件的每一行中删除一些东西,例如:-

我在文件中有以下路径:

/var/lib/svn/repos/b1me/products/payone/generic/code/core/db/fs-type /var/lib/svn/repos/b1me/products/payone/generic/code/fees/ db/fs-type /var/lib/svn/repos/b1me/products/payone/generic/code/merchantserver/db/fs-type

我想做点什么来成为

/var/lib/svn/repos/b1me/products/payone/generic/code/core/ /var/lib/svn/repos/b1me/products/payone/generic/code/fees/ /var/lib/ svn/repos/b1me/products/payone/generic/code/merchantserver/

【问题讨论】:

  • 那么,您想删除db/fs-type 部分,对吗?
  • 是的,我想删除 db/fs-type 部分

标签: linux command-line file


【解决方案1】:
sed 's#db/fs-type$##' myfile > myalteredfile

【讨论】:

  • 请你举个例子
  • 您的 sed 不会删除文件每一行中所有出现的字符串,请添加 'g' 开关...
  • @eumiro 从示例中可以明显看出他想将它们从行尾删除。
  • @Mohammed 这是一个例子。如果信息在myfile 中,您将在同一目录中使用上述sed 命令,它将生成myalteredfile,即您所做更改的副本。
  • 我们可以使用 cat FILENAME | sed -e 's/db\/fs-type//g'
【解决方案2】:

您可以使用一些编辑器(如 nano、vi、vim 等)重写文件,也可以按照本网站的说明进行操作:

http://www.liamdelahunty.com/tips/linux_search_and_replace_multiple_files.php

或者用一个简单的 grep 替换一个字符串,像这样:

http://www.debianadmin.com/howto-replace-multiple-file-text-string-in-linux.html

当我说重写时,我的意思是将“:-”替换为“”...

【讨论】:

    【解决方案3】:
    so ross$ a=/x/y/db/fs-type
    so ross$ b=${a%/db/fs-type}
    so ross$ echo $b
    /x/y
    

    所以现在要做整个文件...

    so ross$ expand < dbf.sh
    #!/bin/sh
    t=/db/fs-type
    while read f1 f2 f3; do
      echo ${f1%$t} ${f2%$t} ${f3%$t}
    done
    so ross$ cat dbf
    /a/b/db/fs-type /c/d/db/fs-type /e/f/db/fs-type
    /a/b/db/fs-type /c/d/db/fs-type /e/f/db/fs-type
    /a/b/db/fs-type /c/d/db/fs-type /e/f/db/fs-type
    /a/b/db/fs-type /c/d/db/fs-type /e/f/db/fs-type
    so ross$ sh dbf.sh < dbf
    /a/b /c/d /e/f
    /a/b /c/d /e/f
    /a/b /c/d /e/f
    /a/b /c/d /e/f
    so ross$ 
    

    【讨论】:

      【解决方案4】:

      我可能会使用sed。经过一些实验,我得到了以下结果

      sed 's:/db/fs-type:/ :g' path.txt
      

      生产

      /var/lib/svn/repos/b1me/products/payone/generic/code/core/ /var/lib/svn/repos/b1me/products/payone/generic/code/fees/ /var/lib/ svn/repos/b1me/

      这似乎是您想要的输出,假设 path.txt 包含您想要更改的原始路径。

      如果你想在另一个文件中捕获它,命令应该是这样的:

      sed 's:/db/fs-type:/ :g' path.txt > new_path.txt
      

      【讨论】:

        【解决方案5】:

        perl 中的一个 :)

        cat oldfile.txt | perl -nle "s/db\/fs-type//g; print;" &gt; newfile.txt

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-22
          • 2011-01-31
          • 2016-02-14
          • 2019-08-24
          • 1970-01-01
          • 2021-09-09
          • 2013-08-23
          • 1970-01-01
          相关资源
          最近更新 更多