插入新条目时对列表重新编号

插入新条目时对列表重新编号

我有一个包含编号条目的文本文件:

1. foo
2. bar 100%
3. kittens
4. eat cake
5. unicorns
6. rainbows

依此类推,直到某个大数字。然后在一个空行之后,一个新的块从 1 开始。

我插入一个新条目,替换例如 4。并且我需要对块中的所有后续条目重新编号:

1. foo
2. bar 100%
3. kittens
4. sunshine <
5. eat cake
6. unicorns
7. rainbows

答案1

您始终可以使用语法添加新条目x. newentry,然后使用以下内容重新编号所有内容:

awk -F . -v OFS=. '{if (NF) $1 = ++n; else n = 0; print}'
  • -F .:将字段分隔符设置为.1
  • -v OFS=.: 同样的输出字段分隔符(-F .的缩写-v FS=.)。
  • {...}: 不状况所以里面的代码{...}是为每一行运行的
  • if (NF),如果字段数大于 0。对于FSbeing .,这意味着当前行是否至少包含一个.。我们还可以让它if (length)检查非空行。
  • $1 = ++n:将第一个字段设置为递增n(最初为 0,然后为 1,然后为 2...)。
  • else n = 0: else (当 NF == 0 时) 将 n 重置为 0。
  • print:打印(可能修改过的)行。

1语法是,-F <extended-regular-expression>但当<extended-regular-expression>是单个字符时,不将其视为正则表达式(其中.表示任何字符),而是将其视为该字符。

答案2

可以通过以下方式获得最大的杀伤力(以及复杂性!和错误!)文本::自动套用格式Perl 模块。

% < input                                                                    
1. foo
2. bar 100%
3. kittens
4. it is getting dark. there may be a grue
4. no seriously, it's getting dark
4. really, you should find a light or something.
4. are you even paying attention? helloooo
4. eat cake
5. unicorns
6. rainbows
% perl -MText::Autoformat -0777 -ple '$_=autoformat $_, { all => 1 }' < input
 1. foo
 2. bar 100%
 3. kittens
 4. it is getting dark. there may be a grue
 5. no seriously, it's getting dark
 6. really, you should find a light or something.
 7. are you even paying attention? helloooo
 8. eat cake
 9. unicorns
10. rainbows
% 

实际结果将取决于输入、期望的输出、通过的选项等。

答案3

VIM解决方案

有两种解决方案:一种是通过在Ctrla选择上自动按键,第二种是通过在submatch(0)+1选择上执行模式替换。首先是关键的自动化。

首先创建您的列表:

1. foo
2. bar 100%
3. kittens
4. eat cake
5. unicorns
6. rainbows

插入一个条目

1. foo
2. bar 100%
3. kittens
4. eat cake
4. sunshine
5. unicorns
6. rainbows

将光标置于4. sunshine命令模式上,然后按shift+ v,然后shift按 + g。这是直到文件末尾的视觉选择。您还可以按照通常的方式将光标移动到块的末尾。

:进入命令模式,您将看到::'<,'> 。现在输入以下内容:

norm Ctrl+ V Ctrl+A

Ctrl-v 和 ctrl-A 的作用是,它们允许您输入“精确”键,因此它会变成^A,突出显示。这基本上是说for all lines selected, execute in normal mode keypress Ctrl-A,并且 Ctrl-A 默认情况下会增加光标下的数字。你会看到数字发生变化

实际解决方案:

在此输入图像描述

在此输入图像描述


另一种方法是从第一个重复的数字中选择所有内容,例如 before( Shiftv, then G),然后进入命令模式执行:

:'<,'>s/\v(^\d+)\./\=(submatch(0)+1).'.'/ 

答案4

删除数字:cut -d" " -f2- < list.txt > temp.txt

将行插入到 temp.txt

制作数字:cat -n temp.txt| sed -e 's/^[ ]*\([0-9]*\)[ \t]*\(.*\)/\1. \2/' > list.txt

相关内容