I have got problems saving sed changes to the same file in a loop.
Basically I want the delimited value in every line of the file to be set to blank according to the value stored in var. var can be changed anytime.
I do not have sed -i and i've tried to mv the file. Any other ideas?
You need double quotes around the sed, otherwise the shell won't expand $i.
Also, after deleting each field, you need to subtract 1 from other field numbers (what was field 2, after deleting field 1, will now be the new field 1).
And for it to work on the last field, you need either to modify the sed, or add a semi-colon to the end of the line:
$ cat sedTest
file=file1
temp=file1.out
var="1;6"
IFS=";"
X=0
for i in $var
do
I=$((i - X))
sed "s/$/;/;s/[^;][^;]*;/;/$I;s/;$//" $file> $temp
X=$((X + 1))
mv $temp $file
done
cat $file
$ ./sedTest
;31-JUL-10;29-JUL-10;29-JUL-10;30-JUL-10;
;31-JUL-10;29-JUL-10;29-JUL-10;30-JUL-10;
;31-JUL-10;29-JUL-10;29-JUL-10;30-JUL-10;
$ # with var="1;2"
$ ./sedTest
$ ./sedTest
;;29-JUL-10;29-JUL-10;30-JUL-10;30-JUL-10
;;29-JUL-10;29-JUL-10;30-JUL-10;30-JUL-10
;;29-JUL-10;29-JUL-10;30-JUL-10;30-JUL-10
yes, to clarify, i need the variable to store the position of the place that i need to be blank, not just the first 2 fields, of which scottn's example works beautifully. thanks.
Hi, your original idea seems sound to me except for the double quotes as scottn suggested, plus you need a revised regex syntax so that the operations are restricted to the intended fields:
var="1;2"
IFS=";"
for i in $var
do
sed "s/[^;]*;/;/$i" $file > $temp && mv $temp $file
done