If else statement in sed

Hello Guys,
I am new here and this is my first post, hope someone can help me

I am writing a script that is supposed to go in 9 different directories and edit a given file in each of the directories. I am using sed to edit the file as

sed -i 'line# s/#to be changed/#to be replaced with/ filename

but to get to the file in each directory I am using an if statement as

for i in {dir1,dir2,...,dir9}
do 
cd $i
if [ "$i" == "dir1" ] ; then
sed -i 'line# s/0/1/ filename
else if [ "$i" == "dir2" ] ; then
sed -i 'line# s/0/2/ filename
else if ...

upto dir9 
fi
cd ..
done

but I always have the error which says unexpected error `done'

can anyone help mw where I am going wrong

thanks

Use elif instead of else if .

And with every sed statement the closing quote is missing. Perhaps you could use a variable so that you only need one sed statement and consider using a case statement.

Thank you very much

Scrutinizer You right or the closing quote, but missed it when I was writing the post. The statement works now fine with if elif statement.
What do yu mean by using only one sed statement?

thanks

If the line numbers, filenames, and string to be replaced are all the same, the directories are literally named "dir<digit>", and the replacement string is the same <digit> as found in the directory name, try:

for i in {1..9}
do      sed -i "line# s/0/$i/" "dir$i/filename"
done

otherwise, try something like:

for i in dir1 dir2 ... dir9
do      cd "$i"
        case "$i" in
        (dir1)   sed -i "dir1line# s/dir1search/dir1repl/" filename1;;
        (dir2)   sed -i "dir2line# s/dir2search/dir2repl/" filename2;;
        ...
        (dir9)   sed -i "dir9line# s/dir9search/dir9repl/" filename9;;
        esac
        cd ..
done
1 Like