Bash script Multiply only numbers from a text file?

I am looking for a bash command that will multiply only numbers from a text file. Below is the content of my text file. I need multiply all numbers by 100.

    0 4530000 sil
4530000 11100000 ow
11100000 6320000 p
6320000 7600000 ah
7600000 8410000 n
8410000 12100000 sil

For single line with only number,I am using something like this below

for file in *.txt; 
do y=`sed -n '1 p' "$file"`;
   z=$(bc<<<"$y*100")
   sed $file -i -e 's/'"$y"'/'"$z"'/'
done

But I dont know how to do it for multiple lines, with alphabets in them. Number of lines in my file are not fixed, each file has different number of lines with max being 8

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Can use perl

perl -pe 's/b(d+.)?d+b/$&*100/ge' file

Method 2

Multiplying all numbers by 100, for integers, means adding 00 to the end of each number if >0.

sed 's/[1-9][0-9]*/&00/g' infile

Method 3

With GNU or busybox awk, recognising numbers like 1.2, .123e-4:

awk -v CONVFMT=%.19g 
    -v RS='\<[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\>' 
    -v ORS= 'RT != "" {RT *= 100}; {print $0 RT}'

You may want to adapt CONVFMT for the format of the numbers.

Method 4

You can use awk. Save this as parse.awk:

{
  for (i = 1; i <= NF; ++i) {
    number = match($i, /[0-9]+(.[0-9]+)?/)
    printf number? "%g " : "%s ", number? $i * 100 : $i
  }
  printf "n"
}

And then run:

awk -f parse.awk file

Or if you want a one-liner:

awk '{for(i=1;i<=NF;++i){n=match($i,/[0-9]+(.[0-9]+)?/);printf n?"%g ":"%s ",n?$i*100:$i} printf"n"}' file


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x