3

I have ASCII file contain numbers as follow:

1 2 3
5 6 9
7 8 9 
. . . 
. . . 
. . . 
. . . 
. . .  etc

I want to upgrade this file by multiplying each value by "3" to get :

3 6 9
15 18 27
21 24 27 
. . . 
. . . 
. . . 
. . . 
. . .  etc

I want these changes to be updated and saved automatically in the same ASCII file after running the script

How can I accomplish this using standard GNU utilities? I can update the values by doing:

while IFS=",$IFS" read d1 d2 d3; do 
echo $(( $d1*3 )) $(( $d2*3 )) $(( $d3*3 )) 
done < file.txt #file.txt is the previous ASCII file
3
  • Are the input numbers all individually less than 10?
    – Jeff Schaller
    Commented Jun 11, 2016 at 18:00
  • 1
    Also, bash is a shell, not a text processor. What other tools are acceptable? Standard GNU utilities?
    – Jeff Schaller
    Commented Jun 11, 2016 at 18:01
  • It'd be good to have representative data in the Q
    – Jeff Schaller
    Commented Jun 11, 2016 at 18:03

2 Answers 2

3

use awk:

$awk -F" "  '{$1*=3;$2*=3;$3*=3;print}' FILE | sponge FILE
$cat FILE
3 6 9
15 18 27
21 24 27
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0

update: you can use sponge program to write output in input FILE

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constricting pipelines that read from and write to the same file.

2
  • @goro : UPDATED :)
    – Baba
    Commented Jun 11, 2016 at 18:02
  • 1
    if you don't have sponge, you can redirect output to a temporary file and then replace the original file with th the temp file (e.g. with mv or cp or cat tempfile > originalfile, etc)
    – cas
    Commented Jun 12, 2016 at 9:39
1

This way you can save new values to file:

awk -F" "  '{$1*=3;$2*=3;$3*=3;print}' FILE | tee FILE
1
  • I assume that destroys content of FILE.
    – Cyrus
    Commented Jun 11, 2016 at 18:17

You must log in to answer this question.