【问题标题】:Removing a specific line in bash with an exact string使用确切的字符串删除 bash 中的特定行
【发布时间】:2021-07-10 01:32:50
【问题描述】:

我无法让 sed 仅删除我想要的特定行。假设我有一个如下所示的文件:

testfile
testfile.txt
testfile2

目前我正在使用它来删除我想要的行:

sed -i "/$1/d" file

问题是,如果我将 testfile 作为输入,它将删除所有三行,但我希望它只删除第一行。我该怎么做?

【问题讨论】:

  • 该命令已经删除了所有三行。
  • I want it to only remove the first line 基于什么条件?仅匹配整行,仅匹配末尾等?另外,您想将输入视为正则表达式还是字符串?比如你传t..tf..e,第一行是不是应该删掉?

标签: sed


【解决方案1】:

使用 grep

grep -x -F -v -- "$1" file
# or
grep -xFv -- "$1" file

-F 用于“固定字符串”——关闭正则表达式引擎。
-x 用于匹配整行。
-v 用于“除”匹配行之外的所有内容。
-- 表示选项结束,以防 $1 以连字符开头。

保存文件

grep -xFv -- "$1" file | sponge file     # `moreutils` package

# or
tmp=$(mktemp)
grep -xFv -- "$1" file > "$tmp" && mv "$tmp" file

【讨论】:

    【解决方案2】:

    所以匹配整行。

    var=testfile
    sed -i '/^'"$var"'$/d' file
    # or with " quoting
    sed -i "/^$var\$/d" file
    

    您可以使用正则表达式填字游戏在线有趣地学习正则表达式。

    【讨论】:

      猜你喜欢
      • 2011-08-21
      • 1970-01-01
      • 2019-12-03
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 2021-12-10
      • 2019-10-09
      相关资源
      最近更新 更多