将数字添加到文件中每一行的开头

发布于 2024-12-16 20:52:57 字数 169 浏览 4 评论 0原文

如何将数字添加到文件中每一行的开头?

例如:

This is
the text
from the file.

变成:

000000001 This is
000000002 the text
000000003 from the file.

How can I add numbers to the beginning of every line in a file?

E.g.:

This is
the text
from the file.

Becomes:

000000001 This is
000000002 the text
000000003 from the file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

度的依靠╰つ 2024-12-23 20:52:57

不要使用 cat 或任何其他不是为此目的设计的工具。使用该程序:

nl - 文件行数

示例:

$ nl --number-format=rz --number-width=9 foobar
$ nl -n rz -w 9 foobar # short-hand

因为 nl 是为此而设计的;-)

Don't use cat or any other tool which is not designed to do that. Use the program:

nl - number lines of files

Example:

$ nl --number-format=rz --number-width=9 foobar
$ nl -n rz -w 9 foobar # short-hand

Because nl is made for it ;-)

指尖凝香 2024-12-23 20:52:57

AWK 的 printfNR$0 可以轻松精确且灵活地控制格式:

~ $ awk '{printf("%010d %s\n", NR, $0)}' example.txt
0000000001 This is
0000000002 the text
0000000003 from the file.

AWK's printf, NR and $0 make it easy to have precise and flexible control over the formatting:

~ $ awk '{printf("%010d %s\n", NR, $0)}' example.txt
0000000001 This is
0000000002 the text
0000000003 from the file.
赠我空喜 2024-12-23 20:52:57

您正在寻找 nl(1) 命令:

$ nl -nrz -w9  /etc/passwd
000000001   root:x:0:0:root:/root:/bin/bash
000000002   daemon:x:1:1:daemon:/usr/sbin:/bin/sh
000000003   bin:x:2:2:bin:/bin:/bin/sh
...

-w9 要求输入九位数长的数字; -nrz 要求将数字格式化为右对齐并用零填充。

You're looking for the nl(1) command:

$ nl -nrz -w9  /etc/passwd
000000001   root:x:0:0:root:/root:/bin/bash
000000002   daemon:x:1:1:daemon:/usr/sbin:/bin/sh
000000003   bin:x:2:2:bin:/bin:/bin/sh
...

-w9 asks for numbers nine digits long; -nrz asks for the numbers to be formatted right-justified with zero padding.

鲜肉鲜肉永远不皱 2024-12-23 20:52:57

cat -n thefile 可以完成这项工作,尽管数字的格式略有不同。

cat -n thefile will do the job, albeit with the numbers in a slightly different format.

画中仙 2024-12-23 20:52:57

最简单、最简单的选择是

awk '{print NR,$0}' file

请参阅上面的评论,了解为什么 nl 并不是真正的最佳选择。

Easiest, simplest option is

awk '{print NR,$0}' file

See comment above on why nl isn't really the best option.

遮云壑 2024-12-23 20:52:57

这是一个 bash 脚本,也可以执行此操作:

#!/bin/bash
counter=0
filename=$1
while read -r line
do
  printf "%010d %s" $counter $line
  let counter=$counter+1
done < "$filename"

Here's a bash script that will do this also:

#!/bin/bash
counter=0
filename=$1
while read -r line
do
  printf "%010d %s" $counter $line
  let counter=$counter+1
done < "$filename"
猥︴琐丶欲为 2024-12-23 20:52:57
perl -pe 'printf "%09u ", $.' -- example.txt
perl -pe 'printf "%09u ", $.' -- example.txt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文