Replace first occurrence of a string in while loop

####Solved####
Hello,
My aim is to replace searched string with incremented value under ubuntu 16.04.
Example:

aasasasas 9030 31wwo weopwoep
weerasas 9030 ew31wo ieopwoep
bbqqqsas 9030 ew3swo ieeopwoep
ccsaqpas 9030 ewiro o2opwoep

Expected:

aasasasas 9030 31wwo weopwoep
weerasas 9031 ew31wo ieopwoep
bbqqqsas 9032 ew3swo ieeopwoep
ccsaqpas 9033 ewiro o2opwoep

I know, what I tried is logically not true:

i=9029
while read -r line
do
i=$i++
sed -i '0,/9030/{s/9030/$i/}' example 
done<example > expected

Is it possible to get expected output with sed ?

EDIT: I tried below command but it starts from 1:

cat example |  awk '/9030/{count++; { sub("9030",count, $0)}; }; {print }'

Final Edit:

cat example |  awk '/9030/{count++; { sub("9030",count+9029, $0)}; }; {print }'

I'd appreciate you help
Thank you
Boris

1 Like

Hello baris35,

Very good that you have solved your question by yourself and appreciate that you have shared with us too, keep it up :b:
You could better your solution by doing this:

awk '{sub("9030",$2+count++,$2)} 1'   Input_file

OR

awk '$2==9030{$2=$2+count++} 1'  Input_file

Output will be as follows.

aasasasas 9030 31wwo weopwoep
weerasas 9031 ew31wo ieopwoep
bbqqqsas 9032 ew3swo ieeopwoep
ccsaqpas 9033 ewiro o2opwoep

Thanks,
R. Singh

1 Like

$2==9030 is quite precise, compared to /9030/ where 9030 can appear as string or substring in all columns.
Back to the while loop. The read command can split the columns into variables

i=9029
while read -r col1 col2 remainder
do
  i=$(( i+1 ))
  if [ "$col2" = 9030 ]
  then
    col2=$i
  fi
  echo "$col1 $col2 $remainder"
done < example > expected

Sometimes it makes sense to use a case-esac.
The $(( )) can contain a modification of the variable.

i=9029
while read -r col1 col2 remainder
do
  case $col2 in
  ( 9030 )
    col2=$(( i+=1 ))
  ;;
  esac
  echo "$col1 $col2 $remainder"
done < example > expected

BTW here, like in your final awk solution, the $i is not incremented if there is no 1930
(Comment for the experts: bash-2 and ksh88 need i+=1 rather than ++i)

1 Like