I'm developing a script, and it perform calculations that need to include in a text file already filled.The format of the file lines is:1 20/10/16 12:00 take car in the garage joe's garageInside the script I get a number from calculations, and that number will replace the first number of the row. For example, the calculate returns the value 15, then the script must access the file in question and change the row in question should look like this:15 20/10/16 12:00 take car in the garage joe's garageThe point is that I do not know how to accomplish this change. It can be in bash, awk, sed, or any available resource. Thank you.
Editing files with shell script
bash;shell script;text processing;awk
How about:awk -v old=$oldNum -v new=$newNum \'{if ($1==old) {$1=new; print} else {print}}' input.txt > output.txtTried it like this:$ cat input.txt2 19/10/16 15:30 some other line1 20/10/16 12:00 take car in the garage joe's garage3 17/10/16 5:30 another one$ oldNum=2$ newNum=15Run the awk command, then:$ cat output.txt15 19/10/16 15:30 some other line1 20/10/16 12:00 take car in the garage joe's garage3 17/10/16 5:30 another oneIs this what you wanted ? If you want your result to appear in the original file, just mv the output file with new name input.txt, that should overwrite the input file (use an anti-slash \mv to avoid aliasing of the mv command).NOTE: you can probably obtain the same result with shorter awk instructions, but this syntax makes it more readable. sed can probably do it in an even more concise way.EDIT: I realise this works if you want to change only 1 number within your file. If I understand your problem correctly, you want to re-calculate the number for every line and create a file with those new numbers. The optimal way of doing that would be to include your calculation of new line number inside the awk script, that way you don't have to create a shell loop, which is generally a bad idea since calling tools like awk, echo, sed... repeatedly ends up being very costly. You could do something like this:if [ -f $PWD/output.txt ]; then     # Remove old output if present in current directory    \rm -f $PWD/output.txtfiawk '{ ###calculation here, result store in newNum###; $1=newNum; print}' input.txt > output.txtFor example, if I want to trivially just increment by one every line number:awk '{$1++; print}' input.txt > output.txtIf you cannot (or dare not) include your calculation inside awk, you can do a loop on the file, but that's pretty clumsy from what I understand of bash scripting:if [ -f $PWD/output.txt ]; then     # Remove old output if present in current directory    \rm -f $PWD/output.txtfiwhile read linedo    newNum=###Calculation here for current line###    echo $line | awk -v new=$newNum '$1=new' >> output.txtdone <input.txt