I have txt file demo.txt
in which multiple values are there like:
A455243X99
A455243X12
A455243X67
A455243X45
And I want fetch these values from this txt file and provide them as an input for another script run.sh
.
#! /bin/bash
echo "repo $value" >> output.txt #$value should start from first line value
echo "repo $value" >> output.txt #$value should keep incrementing according to the text file and
#fetch next value stored in it.
echo "repo $value" >> output.txt
echo "repo $value" >> output.txt #$value should stop incrementing hitting the last line.
I have tried foreach and line but not may be using it wrong, so if anyone has any solution over it or any workaround it would be great.
Note- Need only shell script is allowed, bash or any other platform is not supported.
CodePudding user response:
Use a while loop that reads the file demo.txt line by line:
while read line; do
echo "repo $line" >> output.txt
done < demo.txt
CodePudding user response:
while read value; do echo "repo $value"; done < demo.txt > output.txt
Note the behavior here is slightly different than your sample code, but I believe is the behavior you desire. By using the >
redirect, the output file will be initially truncated rather than having data appended to it. If you do want to append, you can use >>
, but I suspect you are only doing that on subsequent lines to retain previous output from the script. Generally, having multiple lines with the same redirect is an indication of poor coding as it is difficult to maintain and error prone.
But I suspect you have an XY problem here. (eg, the actual problem you are trying to solve is not the problem you've presented.) Using a while read
loop in the shell is extremely inefficient, as the shell will make read one character at a time from its input stream. bash
has mechanisms to improve that, but such things are not very portable. For the particular problem you describe, you would do better to write:
sed 's/^/repo /' demo.txt > output.txt
Whatever your actual problem is, there is probably a solution to it that would be better than the while read
loop.