I'm a beginner in bash and here is my problem. I have a file just like this one:
Azzzezzzezzzezzz...
Bzzzezzzezzzezzz...
Czzzezzzezzzezzz...
I try in a script to edit this file.ABC letters are unique in all this file and there is only one per line.
I want to replace the first e of each line by a number who can be :
1in line beginning with anA,2in line beginning with aB,3in line beginning with aC,
and I'd like to loop this in order to have this type of result
Azzz1zzz5zzz1zzz...
Bzzz2zzz4zzz5zzz...
Czzz3zzz6zzz3zzz...
All the numbers here are random int variables between 0 and 9. I really need to start by replacing 1,2,3 in first exec of my loop, then 5,4,6 then 1,5,3 and so on.
I tried this
sed "0,/e/s/e/$1/;0,/e/s/e/$2/;0,/e/s/e/$3/" /tmp/myfile
But the result was this (because I didn't specify the line)
Azzz1zzz2zzz3zzz...
Bzzzezzzezzzezzz...
Czzzezzzezzzezzz...
I noticed that doing sed -i "/A/ s/$/ezzz/" /tmp/myfile will add ezzz at the end of A line so I tried this
sed -i "/A/ 0,/e/s/e/$1/;/B/ 0,/e/s/e/$2/;/C/ 0,/e/s/e/$3/" /tmp/myfile
but it failed
sed: -e expression #1, char 5: unknown command: `0'
Here I'm lost.
I have in a variable (let's call it number_of_e_per_line) the number of e in either A, B or C line.
Thank you for the time you take for me.
0,/e/? Remove it. just/A/s/e/$1/. If it not readable, consider/A/{ s/e/$1/; };for some readabilitysedis a poor choice here becausesedcan't count. While less efficient, you would be better served by reading each line and making the substitution based on the line number, e.g.c=1; while read -r line; do sed "s/e/1/$c" <<< "$line"; ((c++)); done < file/A/s/e/$1/would replace all theeof the line and not only the first one. In fact your proposition worked perfectly as I wanted it.scommand replaces the first occurrence (by default).c=1; while read -r line; do sed -i "s/e/1/$c" /tmp/myfile <<< "$line"; cat /tmp/myfile; ((c++)); done < /tmp/myfileadding-ito modify myfile and acat myfilethus I can see what happen each time i go throw the loop. The result is that : the firsteof all my lines are replaced by 1 the first time in loop, the second time it's the secondethat are left,...(e.g. :zzzezzzezzzezzzezzzezzzezzzezzzewill bezzz1zzzezzz1zzzezzzezzz1zzze...)