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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8206370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:12:58  来源:igfitidea点击:

Add numbers to the beginning of every line in a file

bashrow-number

提问by Village

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.

采纳答案by Raymond Hettinger

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

AWK 的printfNR$0可以轻松地对格式进行精确和灵活的控制:

~ $ awk '{printf("%010d %s\n", NR, 
nl --number-format=rz --number-width=9 foobar
)}' example.txt 0000000001 This is 0000000002 the text 0000000003 from the file.

回答by tamasgal

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

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

nl - number lines of files

nl - 文件行数

Example:

例子:

$ 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
...

Because nl is made for it ;-)

因为 nl 是为它而生的 ;-)

回答by sarnold

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

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

awk '{print NR,
perl -pe 'printf "%09u ", $.' -- example.txt
}' file

-w9asks for numbers nine digits long; -nrzasks for the numbers to be formatted right-justified with zero padding.

-w9要求九位数的数字;-nrz要求数字以零填充右对齐。

回答by duskwuff -inactive-

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

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

回答by egorulz

Easiest, simplest option is

最简单、最简单的选择是

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

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

请参阅上面关于为什么 nl 不是最佳选择的评论。

回答by Peter John Acklam

##代码##

回答by slashdottir

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

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

##代码##