1

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

4

Can use perl

perl -pe 's/\b(\d+\.)?\d+\b/$&*100/ge' file
  • Yes. I can use perl although I'm not familiar. Can you write full code with 'for loop', that works for each text file? Also do explain each character. – abhinandanbr Oct 26 '17 at 12:33
  • That's it, put that in your loop and remove everything else. Add -i to the flags if you want inplace replacement. – 123 Oct 26 '17 at 12:35
  • I would appreciate if you could also explain what the slashes along with alphabets mean. – abhinandanbr Oct 26 '17 at 12:40
  • @abhinandanbr do you know how sed replacement works? – 123 Oct 26 '17 at 12:41
  • Actually I am not aware of it. – abhinandanbr Oct 26 '17 at 12:43
1

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
1

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.