0

I have to make a shift in some energy values, where the first entry of each file (num.xsf) is :

# total energy = -155.000000 eV

I made a little script to do this, and when I use it without the loop it works. The script:

# Change in -0.029
for file in *.xsf; do
        E=$(head -n 1 $file | cut -d " " -f 5)  #Filter E0
        E_c=$(echo "$E-0.029" | bc)             
        sed "s/$E/$E_c/1" $file > $file; done   # Replace num.xsf > num.xsf
        

I expect to have the same files but the energy line changed to: # total energy = -155.029000 eV, but this saves an empty file. how can I fix this?

  • 2
    your `sed` call is reading/from and writing/to the same file ... a general no-no; either write the output to a different file or if using `GNU sed` you can use the `-i` flag to update the original file (under the hood it actually uses an intermediate temp file), eg: `sed -i "s/$E/$E_c/1" $file` – markp-fuso Sep 23 '22 at 22:15

1 Answers1

0

Use a different file for input and output, otherwise you are overwriting it before sed starts

sed "s/$E/$E_c/1" $in_file > $out_file
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • (1) Consider quoting -- _at least_ `"$in_file"`, perhaps `"$out_file"` as well ("perhaps" on account of the attendant bugs in the redirection case being version-dependent and fixed in new enough shell releases). (2) Consider the obligatory grumbling about answering obvious duplicates to have taken place. – Charles Duffy Sep 23 '22 at 22:49