【问题标题】:Bash: replace list of numbers in column with sequential listBash:用顺序列表替换列中的数字列表
【发布时间】:2013-12-09 14:38:43
【问题描述】:

我需要用序列号列表替换第一列数字。该文件如下所示:

 1     the   quick   brown     fox   jumps    over  
 7     the    lazy     dog     the   quick   brown
13     fox   jumps    over     the    lazy     dog
26     the   quick   brown     fox   jumps    over
31     the    lazy     dog     the   quick   brown

我需要:

 1     the   quick   brown     fox   jumps    over  
 2     the    lazy     dog     the   quick   brown
 3     fox   jumps    over     the    lazy     dog
 4     the   quick   brown     fox   jumps    over
 5     the    lazy     dog     the   quick   brown

任何带有 bash/sed/awk 的解决方案都将不胜感激。

【问题讨论】:

  • Sed 不是最好的工具,因为内部处理湖除了用其他替换模式(不计,...)。与使用简单命令的 awk 相比可能但非常繁重

标签: bash sed awk


【解决方案1】:

使用awk

awk '$1=NR' OFS="\t" file
1       the     quick   brown   fox     jumps   over
2       the     lazy    dog     the     quick   brown
3       fox     jumps   over    the     lazy    dog
4       the     quick   brown   fox     jumps   over
5       the     lazy    dog     the     quick   brown

由于NR 始终是大于0 的数字,因此这将始终为真并被打印出来。
您可以使用'{$1=NR}1{$1=NR;print $0} 使其更具可读性。

【讨论】:

  • 哇,你的人更好..我不知道我们可以简单地这样写。 \m/
【解决方案2】:

尝试使用 awk 变量 NR,它会为您提供正在处理的记录号。
如果您想要示例代码,请参见下文:
假设文件有这样的记录

1 ask
5 rup
6 dd


现在运行以下命令:

 awk '{ print NR FS $2 }' filename


输出:

1 ask
2 rup
3 dd


休息我留给你弄清楚

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 2012-11-22
    • 1970-01-01
    • 2018-10-06
    • 2022-11-30
    • 2023-01-11
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多