0

I am trying to do some math on 2nd column of a txt file , but some lines are not numbers , i only want to operate on the lines which have numbers .and keep other line unchanged

txt file like below

aaaaa 
1 2
3 4

How can I do this?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
zrebot
  • 51
  • 2
  • 5
  • 1
    Please confirm that you want a _pure Bash_ solution - as opposed to calling standard Unix utilities such as `awk` from Bash. – mklement0 Jan 20 '16 at 03:15
  • 2
    Arguably, given an answer to http://stackoverflow.com/questions/806906/how-do-i-test-if-a-variable-is-a-number-in-bash/806923#806923 this becomes trivial. – Charles Duffy Jan 20 '16 at 03:15

2 Answers2

1

Doubling the second column in any line that doesn't contain any alphabetic content might look a bit like the following in native bash:

#!/bin/bash

# iterate over lines in input file
while IFS= read -r line; do
  if [[ $line = *[[:alpha:]]* ]]; then
    # line contains letters; emit unmodified
    printf '%s\n' "$line"
  else
    # break into a variable for the first word, one for the second, one for the rest
    read -r first second rest <<<"$line"

    if [[ $second ]]; then
      # we extracted a second word: emit it, doubled, between the first word and the rest
      printf '%s\n' "$first $(( second * 2 )) $rest"
    else
      # no second word: just emit the whole line unmodified
      printf '%s\n' "$line"
    fi
  fi
done

This reads from stdin and writes to stdout, so usage is something like:

./yourscript <infile >outfile
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

thanks all ,this is my second time to use this website ,i find it is so helpful that it can get the answer very quickly

I also find a answer below

#!/bin/bash
FILE=$1

while read f1 f2 ;do 

if[[$f1 != *[!0-9]*]];then 
  f2=`echo "$f2 -1"|bc` ;
  echo "$f1 $f2"
else
  echo "$f1 $f2"
fi

done< %FILE

zrebot
  • 51
  • 2
  • 5
  • As given here, this answer doesn't work -- maybe you left out some whitespace when typing it into the form? – Charles Duffy Jan 20 '16 at 05:08
  • 1
    There are other bugs, such as emitting `$2` rather than `$f2` in the output -- and if your intended values are all integers, it would me much more efficient to use built-in math in the shell rather than `bc`: `f2=$(( f2 - 1 ))` – Charles Duffy Jan 20 '16 at 05:10