Home > Net >  How do I copy text from one file, add to it, and put it into another file in Bash Script?
How do I copy text from one file, add to it, and put it into another file in Bash Script?

Time:03-14

I am looking to modify my bash script to include taking text from a location in one file, modifying it, and pasting it in another file. Specifically:

  1. In the file CHGCAR, I am looking to copy three numbers. These numbers will correspond to an X, Y and Z value. The three numbers do not have any words or other text associated with them. The first empty line in the file is between a block of numbers and the desired numbers, as shown.

     0.5 0.64 0.65
     0.5 0.34 0.43
    
     144 108 112
     0.786648293755 0.15544227654 0.75569723224
    

In this example, would like to grab 144, 108 and 112 from the file. Sometimes at least one of the desired numbers may be two digits instead of three. (Note that there are many lines above the top block and below the bottom block of text that contain decimals, and the number of lines in each block can change depending upon the file.) However, the location of the desired numbers relative to the block of text will remain constant between files.

  1. I want to modify the text to add the following to look like:

     NGXF = 144
     NGYF = 108
     NGZF = 112
    
  2. I would then like to paste this text into a new file named INCAR. Ideally, I would like to paste it beneath a line that reads:

     #NGX = 36
    

But if it makes the code significantly easier, I think pasting it at the end of the INCAR file will suffice. The files CHGCAR and INCAR will be located in the same directory.

Thank you in advance!

CodePudding user response:

You will probably need a bash script for this. Either make a file script.sh or copy these lines into bash.

Assuming those numbers are always on the same line, they can be read easily by the sed command. Otherwise, you could read the file line by line and read the numbers after the empty line

#!/bin/bash
# script.sh

infile="CHGCAR"
outfile="INCAR"
# sed -n '4p' gets the 4th line CHGCAR. 
# Parentheses treat the string from sed as an array, splitting it on whitespace.
line4=($(sed -n '4p' $infile))

# write to the file
echo "#NGX = 36" > $outfile
# append to the file
echo "NGXF = ${line4[0]}" >> $outfile
echo "NGYF = ${line4[1]}" >> $outfile
echo "NGZF = ${line4[2]}" >> $outfile
    

CodePudding user response:

This can be done with a bash script. First learn how to make a script, learn the shebang and learn to use the grep bash command with regular expressions(regex) and your echo/cat commands

  • Related