Use shell script to insert a record every 100 rows, and the first column of the record contains the row number, while the other columns remain unchanged

Time:2021-4-20

1. Example: insert a record every 100 rows, and the first column of this record contains the row number, other columns are the same as the first row

#!/bin/sh
Var = "00001" # variable
Cat a.txt | awk 'NR = = 1' | while read line # get the first line of the file
do
    #echo "$line"
    Result = ` echo "$line" | cut - F2 - '; by default, it is divided by tab to get the second column to the last column
    Cat a.txt | awk 'NR% 100 = = 0 {printf (% 04D | n ", NR)}' | while read line # get the line number every 100 lines, the line number is 4 digits, less than 0 
    do
        data=`echo -e "9$line$var\t$result"`
        echo "$line"
        #echo "$result"
        #echo "$data"
        #sed -e "'$line'a\'$data'" a.txt
        Sed - I '$line' a '"$data"', a.txt # insert to file
    done
done

2. Example: replace the data in line 100 every 100 lines

#!/bin/sh
var="abc"
Cat a.txt | awk 'NR% 100 = = 0' | awk '{split ($0, B, "\ T"); print B [2]}' | while read line # read a file and get the second column of current line every 100 lines
do
    #echo "$line"
    Sed - I "s / $line / $var / g" a.txt # replace the above column with a known variable
done

The above is Xiaobian’s introduction to you, using shell script to insert a record every 100 lines, and the first column of the record contains the line number, and other columns remain unchanged. I hope it can help you. If you have any questions, please leave me a message, Xiaobian will reply you in time. Thank you very much for your support to developer!

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]