LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Modifying records of a file using shell scripting (https://www.linuxquestions.org/questions/linux-software-2/modifying-records-of-a-file-using-shell-scripting-727519/)

barunparichha 05-21-2009 07:14 AM

Modifying records of a file using shell scripting
 
$cat file
a 1 2 3
b 2 3 4
c 3 4 5
d 4 5 6

I need to write a script which will read the records of file and increment the 2nd field by 5 and write it back.

$cat script.sh

echo "file name:"
read file

if [ -f $file ]
then
exec 0<$file

while read line
do
#set `cat $line| tr -s " "`
#t=`expr $2 + 1`
f1=`echo $line | cut -d' ' -f1`
f2=`echo $line | cut -d' ' -f2`
f2=`expr $f2 + 5`
f3=`echo $line | cut -d' ' -f3`
f4=`echo $line | cut -d' ' -f4`
echo "$f1 $f2 $f3 $f4" >>tmp
done
mv tmp $file
fi



But
echo $f1 $f2 $f3 $f4 >>tmp, will not work if we have say 100 fields.
i.e writing
echo "$1 $2 .... $100" >>aa

is not a good programming.

Is there any alternate and better way to do so.

colucix 05-21-2009 08:08 AM

A simple awk one-liner can do the trick:
Code:

awk '{sub($2,($2 + 5),$2)}1' file
To answer to your question you can try extended brace expansion to get the sequence of numbers from 1 to 100:
Code:

while read line
do
  #
  #  Read fields from 1 to 100
  #

  for i in {1..100}
  do
    eval "f${i}=$(echo $line | cut -d' ' -f$i)"
  done
  #
  #  Change second field
  #

  f2=$(($f2 + 5))
  #
  #  echo them all
  #

  eval "echo \$f{1..100}"
done


barunparichha 05-21-2009 08:36 AM

I think these brases does not work in my bash.
{1..100}

colucix 05-21-2009 08:48 AM

This means you have a BASH version older than 3. You can try the seq command instead:
Code:

while read line
do
  #
  #  Read fields from 1 to 100
  #

  for i in $(seq 1 100)
  do
    eval "f${i}=$(echo $line | cut -d' ' -f$i)"
  done
  #
  #  Change second field
  #

  f2=$(($f2 + 5))
  #
  #  echo them all
  #

  eval echo $(seq -f"\$f%.0f" 1 100)
done


ghostdog74 05-21-2009 09:09 AM

Code:

awk '{$2+=5}1'  file

barunparichha 05-21-2009 09:33 AM

Now it is working.
Thanks a lot for your help.


All times are GMT -5. The time now is 10:47 AM.