I have the following code but it doesnt work when i execute the code, the file th2.csv its empty. The function of the sed is replace two words. I dont know how to make the script work correctly. It must be done with the while.
bash th1.csv > th2.csv
Script bash
#!/bin/bash
while read -r line; do
echo "$line" | sed -E "s/,True,/,ll,/g;s/,False,/,th,/" th1.csv
done < th1.csv
CodePudding user response:
Given the requirements that you must loop and apply regex, line by line, then consider:
#!/bin/bash
while read -r line; do
echo "$line" | sed -E "s/,True,/,ll,/g;s/,False,/,th,/" >> th2.csv
done < th1.csv
This reads, line by line, via a while loop. Each line is passed as stdin to sed
. Note we remove the th1.csv
at the end of your original sed
attempt, as that will override sed
reading from stdin (causing it to ignore it and instead process the file over and over again, every iteration). Lastly we append >>
to your th2.csv
file each iteration.
Guessing a step ahead, that you may want to pass the two files in as parameters to the script (just based on your first code snippet) then you can change this to:
#!/bin/bash
while read -r line; do
echo "$line" | sed -E "s/,True,/,ll,/g;s/,False,/,th,/" >> "$2"
done < "$1"
And, assuming this script is called myscript.sh
you can call it like:
/bin/bash myscript.sh 'th1.csv' 'th2.csv'
Or, if you make it executable with chmod x myscript.sh
then:
./myscript.sh 'th1.csv' 'th2.csv'.
CodePudding user response:
Use sed -i
to edit file in places.
You can refer to man find