By reading your code I'm confused if these are typing mistakes or real mistakes:
- Variable
file
is assigned (line 5), but called with $File
(line 6)
- Line 6, variable
$1
is called, but it is meaningless because it refers the first argument passed to this script, since you never do the passing, it gives null. Is it $i
instead?
Other issues:
Line 7: No need to use 'g' as there is no more than one match
Cutting your expression into parts with single or double quotes are acceptable (As noted by @JohnKugelman), but, to pass variable to s/old/new/, it's unnecessary to quote the expression unless you need SPACE character in your expression. On the other hand, if there is a word-class character (letters, digits and underline "_") following the position of the variable, just embrace it:
sed -i "1s/7:/${datafile}_7:/" ./File$i.txt
Note for passing variables which contain special symbol like '/', '*', etc., to sed: You need to first escape all these symbols using parameter expansion.
(C.f. external link Passing variables which contain special characters to sed and Bash manual Parameter expansion)
Issue about logic structures:
As @Nic3500 said about. The first for
loop contain 3 loops on i
; the second for
loop contain n loops on your n files in the directory - in total 3*n loops. But your operation needs only n.
It is confusing since you did't say what is the relationship between the File$i.txt and the values "Juan". You just confound them in your example, where, "File1" is a variable but at the same time the file name of "File1.txt". If you really already have a sets of such variables (variable name = file name), you can just:
for i in {1..3}; do
sed -i "1s/7:/$(eval echo \$File$i)_7:/" ./File$i.txt
done
Same way as your script using dynamic variable names.
But this is really frustrating using variables as names of variables and I personally not recommend to. Instead, using an array, I think, is better:
NAME=(Juan Pedro Carlos); # Or other ways to assign this array
for((i=0;i<${#NAME[@]};i++)); do
sed -i "1s/7:/${NAME[$i]}_7:/" ./File$(($i+1)).txt
done