When i try to use line number from variable in sed it works individually but when same is done using while loop it not works.
eg.
cat file
den
run
ten
run
fan
linenumber=2
replacetext=34
sed -i ""$linenumber"s/run/run\n"$replacetext"/" file
Output:
cat file
den
run
34
ten
run
fan
Above works and sed command is generated after variable expansion.
But when i use same in while loop it does work only for first instance and not all as i wanted to replace all instances with incrementing line number using pure sed solution. Awk or perl solution is not wanted.
eg.
replacetext=1
while read in; do replacetext=$((replacetext++)) && sed ""$in"s/run/run\n"$replacetext"/" file; done <<< "$(cat file | grep 'run' -n | cut -f1 -d ':')"
Expected Output: Match text will be replaced with itself followed by newline and a incrementing number.
den
run
2
ten
run
3
fan
Obtained output:
den
run
2
ten
run
fan
Please only sed based solution required. And i wanted to know what unusual behaviour was occuring in while loop that it was not working.Because the loop variable is given the value of line number and then that line number is used in sed to replace macthed text on that line with itself folowed by newline and incremented number.
Sed seems to work when same variable line number is provided but not when used in while loop.
seq 1 "$(wc -l <file)" | sed -i '/run/R/dev/stdin' file
instead. Theseq
just generates a suitably large number of indices and thesed
reads as many of them as it needs.