简体   繁体   中英

Replace specific rows with values from another text file in shell scripting?

I have a file that is 8 rows of single asterixes. I have 4 text files, with two rows of numbers in each. I want to create a new file for each of the text files, where row number i+2 and i+3 is replaced by the content of the text file. For example:

File1 would be:

1 5 7 8  
2 4 5 6  

I want to convert it to:

1 5 7 8  
2 4 5 6  
*  
*  
*  
*  
*  
*  

And File2 would converted from:

6 5 6 7  
8 9 0 9  

to:

*  
*  
6 5 6 7  
8 9 0 9  
*  
*  
*  
*  

Is there a way to iterate through text files in a directory, converting each text file like above?

Thanks!

UPDATE: Maybe this will explain it better:

Basically I have n-number of text files, each having only two rows of numbers. I want to cycle through the text files, converting each text file into another text file where there is nx 2 number of rows, with the first text file's values taking up row 1 & 2 and the rest of the rows are *. The second text file would have nx 2 rows, but the 3rd and 4th row are the files values, with the rest being *. The third file having nx 2 rows, with the 6 & 7th row being populated with its values and rest being *, and so on.

Not sure how to do this easily in shell, but GNU awk has some features that make it pretty straightforward.

parse.awk

BEGINFILE { 
  outfile = ARGV[ARGIND] ".new"
  for(i=1; i<ARGIND; i++)
    print "*\n*" > outfile
} 

{ print > outfile }

ENDFILE { 
  for(i=1; i<ARGC-ARGIND; i++) 
    print "*\n*" > outfile
  close(outfile)
}

Run it like this:

gawk -f parse.awk File*

Explanation

ARGV is an array and holds the names of the input files. ARGIND is the index into ARGV to the file currently being processed, ARGC is the length of ARGV, ie the number of arguments given.

The BEGINFILE and ENDFILE blocks are executed when beginning/finished the processing of a file, so they're convenient hooks in your case.

bash solution:

n=8
i=0
for file in * ; do 
    { 
        for ((a=0 ; a<n ; a++)) ; do
            ((a==i)) && cat "$file"
            echo $'*\n*'
        done
    } > "$file".out
    let i++
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM