在每行的开头添加数字,并将星号替换为文档中的数字

在每行的开头添加数字,并将星号替换为文档中的数字

Linux CentOS 7 有没有办法在文档的行中添加数字。任何方法都可以,命令、代码、脚本等等。我有一个文档,我想对行进行编号。

输入示例

Only I can change my life.
Good, better, best.
Life is 10% what happens to you and 90% how you react to it.

输出

1 Only I can change my life.
2 Good, better, best.
3 Life is 10% what happens to you and 90% how you react to it.

另一个问题

如何更改带有数字的文本开头的星号“*”?

输入

* Only I can change my life.
* Good, better, best.
* Life is 10% what happens to you and 90% how you react to it.

输出

1 Only I can change my life.
2 Good, better, best.
3 Life is 10% what happens to you and 90% how you react to it.

答案1

至号码每一个线,使用荷兰, 这数字L内斯实用程序:

nl -ba input

该标志的含义是:使用ll 行b的 ody 编号样式。a

要仅对非空白行进行编号,请使用:

nl -bt input

nl提供多种格式化数字的功能;默认情况下,它用制表符分隔数字;对于单个空间,请使用-s' '.它还假定数字的默认列宽;如果您不需要这样的填充空间,请使用-w 1.

要用 sed 替换前导字符,请参阅使用 sed 将文件中的所有行替换为行中第一次出现的模式, 例如:

sed 's/^\*//' input

...其中*必须转义,因为它是正则表达式标记,表示前一项的零个或多个。虽然没有前面的项目(它是一个锚点,意味着行的开头),但最好还是避开它。

答案2

要将数字添加到文档中:

cat -b file > output_file
-b, --number-nonblank    number nonempty output lines, overrides -n    

将文件写入标准输出,并添加行号而不是星号。

cat file | sed 's/*//' | nl > output_file

答案3

input:

Only I can change my life.
Good, better, best.
Life is 10% what happens to you and 90% how you react to it


output:

[root@praveen_2 ~]# cat -n input
     1  Only I can change my life.
     2  Good, better, best.
     3  Life is 10% what happens to you and 90% how you react to it.


command:cat -n input


=============================================================================
second questtion

input
* Only I can change my life.
* Good, better, best.
* Life is 10% what happens to you and 90% how you react to it

output

cat -n input| sed 's/\*//g'
     1   Only I can change my life.
     2   Good, better, best.
     3   Life is 10% what happens to you and 90% how you react to it


command:cat -n input| sed 's/\*//g

'

相关内容