【问题标题】:Strange behaviour using `sed`使用`sed`的奇怪行为
【发布时间】:2016-06-01 18:53:45
【问题描述】:

因此,我正在尝试从命令行格式化此表中的数字后删除制表符。以下是原始表格数据,直接从相关文件中复制和粘贴:

File Path                   Line  Description
/home/nick/.bashrc             9         # TODO        Chop this into code import files
/home/nick/.bashrc           204         # TODO        Add $HOME/os-setup to OS installation disc
/home/nick/.bashrc           207         # TODO        Custom power actions don't work; system tray notifications

然而,当向管道添加最终的sed 命令时,会发生一些奇怪的行为。例如,考虑下面的sed 命令:

cat somefile.txt | column -tx -s : | sed -e 's/\([0-9]\{1,\}\)/\1/g'
File Path                   Line  Description
/home/nick/.bashrc             9         # TODO        Chop this into code import files
/home/nick/.bashrc           204         # TODO        Add $HOME/os-setup to OS installation disc
/home/nick/.bashrc           207         # TODO        Custom power actions don't work; system tray notifications

这会在表格的每一行中查找数字,然后将匹配项替换为正则表达式的第一部分。由于整个匹配都用大括号括起来,这意味着它被自己替换后没有任何变化。

但是,当我尝试相同的sed 命令时,我将\t 字符(一个文字制表符)添加到匹配的正则表达式中,sed 输出似乎也截断了数字匹配!见下文:

cat somefile.txt | column -tx -s : | sed -e 's/\([0-9]\{1,\}\)\t/\1/g'
File Path                   Line  Description
/home/nick/.bashrc               # TODO        Chop this into code import files
/home/nick/.bashrc           20  # TODO        Add $HOME/os-setup to OS installation disc
/home/nick/.bashrc           20  # TODO        Custom power actions don't work; system tray notifications

为什么sed 会截断每个数字的最后一位?我怎样才能阻止sed 这样做?

【问题讨论】:

  • 能否请您显示带有 \t 的 sed 代码?
  • 有趣,无法复制
  • @NickBull : 文件从何而来?
  • @sjsam 它本身并不是一个真正的文件,而是我正在帮助维护的一个非常大的 bash 脚本的文本文件中的 grep 命令的输出。

标签: linux bash sed formatting


【解决方案1】:

我没有删除数字后的制表符,而是删除了# TODO 之前的空格。

awk(GNU) 解决方案

awk '{print gensub(/[ ]+(  # TODO)/,"\\1","g",$0)} ' file

sed 解决方案

sed -E 's/[ ]+# TODO/  # TODO/' file

输出

File Path                   Line  Description
/home/nick/.bashrc             9  # TODO        Chop this into code import files
/home/nick/.bashrc           204  # TODO        Add $HOME/os-setup to OS installation disc
/home/nick/.bashrc           207  # TODO        Custom power actions don't work; system tray notification

假设

描述总是以# TODO开头

注意

您可以在选择的# TODO 之前放置所需数量的空格。我放了两个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-28
    • 2021-12-15
    • 1970-01-01
    • 2014-12-27
    • 2012-04-21
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多