English 中文(简体)
预支费用导致每个档案线零。
原标题:Prepend leading zeros to each line of a file

I have a file that looks like this:

1:line1
14:line2
135:line3
15:line4

我需要预先搁置每个线的零点,以便把它看上去:

00001:line1
00014:line2
00135:line3
00015:line4

是否很容易在含水层这样做?

我尝试使用

awk  {printf "%05d:%s
", FNR, $0}  file

但这一产出如下:

00001:1:line1
00002:14:line2
00003:135:line3
00004:15:line4

我应该指出,我没有写过这一指挥,我从谷歌那里听,没有真正理解它是如何运作的。

最佳回答

有许多方法,一种方法是使用<代码>wk。

awk -F":"  {OFS=FS; $1 = sprintf("%05d", $1); print}  "${filename}"

打破僵局:

  • -F":" set the field seperator to ":", awk will split the lines into columns for each :.
  • OFS=FS set the output field separator to the field separator, this essentially puts ":" back into each line when we output it.
  • $1 = sprintf("%05d", $1) set the first column, $1, to be itself padded with 0 s and of length 5.
  • print print the line.
问题回答

使用任何 a子:

$ awk  {p=index($0,":"); printf "%05d%s
", substr($0,1,p-1), substr($0,p)}  file
00001:line1
00014:line2
00135:line3
00015:line4

检查结果(次×至@EdMorton)

awk -F :   {
    p = index($0, ":")
    tag = substr($0, 1, p-1)
    val = substr($0, p+1) 
    # or tag=val=$0; sub(/:.*/,"",tag); sub(/[^:]+:/,"",val)
    printf "%05d:%s
", tag, val
}  input.txt

您有<代码>标签:价值 pairs, 如果您不提KNOW,而完全控制哪些果园价值能包含得较安全的文件p=index(0,”:”; tag=substr(0,p+1美元); val=substr(0,p+1美元)>>>>; 标签=val=0; 次级(/:*/,” 标签); 次级(/[^:]+:/,”=/, val)或类似的

也可以用废墟解决这一问题:

ruby -ne  puts "%05d:%s" % $_.split(":")  input.txt

perl -pe  s/(d+):/sprintf "%05d:", $1/e  input.txt

产出

00001:line1
00014:line2
00135:line3
00015:line4

在<代码>awk中添加另一种方式。 将野外分离器和产出野外分离器定为:,并将空间扩大到第1个领域,使之仅按需要将其分成5个,然后用<代码>0取代每一空间。

awk -F :  -v OFS= :   {$1=sprintf("%5s",$1);gsub(/ /,"0",$1)} 1  Input_file

你可以做到:

awk  BEGIN{FS=OFS=":"} 
{$1=sprintf("%05d", $1)} 1  file 

印刷:

00001:line1
00014:line2
00135:line3
00015:line4

根据评论,冷却版本:

awk  $1=sprintf("%05d", $1)  FS=: OFS=: file
# same

使用该机:

 perl -lpe  s{^d+}{sprintf "%05d", $&}e;  infile > outfile

2. 更换档案:

 perl -i.bak -lpe  s{^d+}{sprintf "%05d", $&}e;  infile

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
-l : Strip the input line separator (" " on *NIX by default) before executing the code in-line, and append it when printing.
-i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak. If you want to skip writing a backup file, just use -i and skip the extension.

The regex uses this modifier:
/e : Evaluate REPLACEMENT as an expression in s/PATTERN/REPLACEMENT/

^ : The beginning of the line.
d+ : One or more digits. The match is captured into variable $&, which we use later inside sprintf.
sprintf "%05d", $& : returns a string where the digits captured in $& are padded with 0s to give a number of length 5.

www.un.org/Depts/DGACM/index_spanish.htm 另见。

核心用途选择:

paste -d: <(printf "%05d
" $(cut -d: -f1 infile)) <(cut -d: -f2- infile)

Here is a python script. Here we are just splitting the line and zfilling the number to the required length.

def format_data(filename: str, int_length: int):
    new_lines = []
    if not os.path.exists(filename):
        print("No file found!")
        return 1
    with open(filename, "r") as fileobj:
        for line in fileobj.readlines():
            try:
                pre, post = line.split(":")
                new_lines.append(f"{pre.zfill(int_length)}:post")
            except Exception:
                print(f"Some error")
                new_lines.append(line)
    write_filename = f"updated_{filename}"
    with open(write_filename, "w") as fileobj:
        fileobj.writelines([string +  
  for string in new_lines])

    print(f"Saved updated file {write_filename}")
    return 0

将职能与档案名称和所需数目的总长度联系起来

    format_data("sample.txt", 5)

产出文件载于<代码>updated_<filename>。

Error in you code is that your print FNR equivalent to Number of Record and $0 (all field). If you set the Field separator (-F=":") field $1 are valued that add zeros, and $2 is the second field with line value. Thus print $1 (to add zero with %05d) into printf statment and $2(line value)

 awk -F":"  {printf "%05d:%s
", $1, $2}  file

添加“以经常表达方式加以说明”的“:”

应分为三个假设情景:

如果次体已完全达到5级,则该次梯度为天线。


如果出现较长但保持准确的超量,则将无所作为。


少于5岁

echo  
1:line1
14:line2
135:line3
15:line4
00000003523532:line5  | 

 mawk  { gsub(/::+/, ":") } ! (_ = 6-index($__, ":")) || 
       $!NF = _<-_ ? substr($__, match($__, /[^0]*.....:/)) 
                   : sprintf("%.*d",_,__) $__  

00001:line1
00014:line2
00135:line3
00015:line4
3523532:line5
  • Solutions utilizing %05d perform both a string-to-num then another num-to-string conversion when neither is needed,

利用<代码>%05d进行更长时间的投入风险,从而改变投入本身;

echo  9992315351235323253252317:line9  | 

gawk  {p=index($0,":"); printf "%05d%s
", substr($0,1,p-1), substr($0,p)} 

               |
9992315351235322445824000:line9 
               |->
9992315351235323253252317:line9
               |             

标线上的所有位数或右边的所有数位数均已通过%05d.bigint腐败,这无疑能够减轻这一风险,但为什么在没有任何东西可以开始的情况下需要减少风险?





相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签