简体   繁体   中英

Modify text file with math expression

I have a file called POSCAR that looks like this.

Pt-FCC                     
3.975                      
3.975000 0.000000 0.000000 
0.000000 3.975000 0.000000 
0.000000 0.000000 3.975000 

I need to change the 3x3x3 matrix several times, to take the following shape and values, where d ranges from 0.005 to 0.025 with a 0.005 increment.

Pt-FCC                    
3.975                      
1+d      0.000000 0.000000
0.000000 1-d      0.000000
0.000000 0.000000 1/(1-d^2)

For example, for d=0.005:

Pt-FCC                    
3.975                      
1.005000 0.000000 0.000000
0.000000 0.995000 0.000000
0.000000 0.000000 1.000025

I cannot assign a variable inside the file and use expr and echo to evaluate it, because the simulation program does not understand this. I am attempting to use a loop that iterates through all the values of d and copies the original POSCAR file, then uses perl, sed, or awk to modify the matrix while keeping the spacing constant.

for i in $(seq 0.005 0.005 0.025)
do
        cp POSCAR POSCAR_pure_shear/POSCAR_pure_$i
        perl -pi .................. POSCAR_pure_$i
done

I understand this is a long question and I appreciate any help that might shift me in the right direction. I am still a beginner!

You can do something like this:

awk -v d=0.005 'FNR==3 {$1=sprintf("%0.6f", 1+d)}
    FNR==4 {$2=sprintf("%0.6f",1-d)}
    FNR==5 {$3=sprintf("%0.6f",1/(1-d**2))}
1' file

Prints:

Pt-FCC                     
3.975                      
1.005000 0.000000 0.000000
0.000000 0.995000 0.000000
0.000000 0.000000 1.000025

Plugging that into your loop:

for i in $(seq 0.005 0.005 0.025)
do
    awk -v d="$i" 'FNR==3 {$1=sprintf("%0.6f", 1+d)}
    FNR==4 {$2=sprintf("%0.6f",1-d)}
    FNR==5 {$3=sprintf("%0.6f",1/(1-d**2))}
    1' file
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