How to insert a new line character after a fixed number of characters in a file

前端 未结 7 446
别那么骄傲
别那么骄傲 2020-12-02 12:16

I am looking for a bash or sed script (preferably a one-liner) with which I can insert a new line character after a fixed number of characters in huge text file.

相关标签:
7条回答
  • 2020-12-02 12:54

    Here is POSIX solution:

    awk '{gsub(/.{5}/,"&\n")}1' file
    

    Or:

    fold -w5 file
    

    Input:

    banana strawberry grape
    

    Output:

    banan
    a str
    awber
    ry gr
    ape
    

    Interestingly, the Awk solution is more performant than fold.

    0 讨论(0)
  • 2020-12-02 12:58

    Because I can't comment directly (to less reputations) a new hint to upper comments:

    I prefer the sed command (exactly what I want) and also tested the Posix-Command fold. But there is a little difference between both commands for the original problem: If you have a flat file with n*bytes records (without any linefeed characters) and use the sed command (with bytes as number (20 in the answer of @Kristian)) you got n lines if you count with wc. If you use the fold command you only got n-1 lines with wc! This difference is sometimes important to know, if your input file doesn't contain any newline character, you got one after the last line with sed and got no one with fold

    0 讨论(0)
  • 2020-12-02 13:00

    How about something like this? Change 20 is the number of characters before the newline, and temp.text is the file to replace in..

    sed -e "s/.\{20\}/&\n/g" < temp.txt
    
    0 讨论(0)
  • 2020-12-02 13:05

    Append an empty line after a line with exactly 42 characters

    sed -ie '/^.\{42\}$/a\
    ' huge_text_file
    
    0 讨论(0)
  • 2020-12-02 13:08

    if you mean you want to insert your newline after a number of characters with respect to the whole file, eg after the 30th character in the whole file

    gawk 'BEGIN{ FS=""; ch=30}
    {
        for(i=1;i<=NF;i++){
            c+=1
            if (c==ch){
                print "" 
                c=0           
            }else{
                printf $i
            }
        }
        print ""
    }' file
    

    if you mean insert at specific number of characters in each line eg after every 5th character

    gawk 'BEGIN{ FS=""; ch=5}
    {
        print substr($0,1,ch) "\n" substr($0,ch)
    }' file
    
    0 讨论(0)
  • 2020-12-02 13:09

    Let N be a shell variable representing the count of characters after which you want a newline. If you want to continue the count accross lines:

    perl -0xff -pe 's/(.{'$N'})/$1\n/sg' input
    

    If you want to restart the count for each line, omit the -0xff argument.

    0 讨论(0)
提交回复
热议问题