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. |
A simple awk one-liner can do the trick:
Code:
awk '{sub($2,($2 + 5),$2)}1' file Code:
while read line |
I think these brases does not work in my bash.
{1..100} |
This means you have a BASH version older than 3. You can try the seq command instead:
Code:
while read line |
Code:
awk '{$2+=5}1' file |
Now it is working.
Thanks a lot for your help. |
All times are GMT -5. The time now is 10:47 AM. |