shoham
shoham

Reputation: 812

iterating through each line and each character in a file

i'm trying to get a file name, and a character index, and to print me the characters with that index from each line (and do it for each character index the user enters if such character exists). This is my code:

#!/bin/bash
read file_name
while read x
do
    if [ -f $file_name ]
    then
            while read string
            do
                    counter=0
                    while read -n char
                    do
                            if [ $counter -eq $x ]
                            then
                                    echo $char
                            fi
                            counter=$[$counter+1]
                    done < $(echo -n "$string")
            done < $file_name
    fi
done

But, it says an error:

line 20: abcdefgh: No such file or directory

line 20 is the last done, so it doesn't help me figure out where is the error.

So what's wrong in my code and how do I fix it?

Thanks a lot.

Upvotes: 0

Views: 112

Answers (3)

Jack
Jack

Reputation: 6158

I think "cut" might fit the bill:

read file_name
if [ -f $file_name ]
then
    while read -n char
    do
        cut -c $char $file_name
    done
fi

Upvotes: 2

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

replace

                counter=0
                while read -n char
                do
                        if [ $counter -eq $x ]
                        then
                                echo $char
                        fi
                        counter=$[$counter+1]
                done < $(echo -n "$string")

with

if [ $x -lt ${#string} ]
then
    echo ${line:$x:1}
fi

It does the same, but allows to avoid such errors.

Another approach is using cut

cut -b $(($x+1)) $file_name  | grep -v "^$"

It can replace two inner loops

Upvotes: 0

anubhava
anubhava

Reputation: 785156

This line seems to be problematic:

done < $(echo -n "$string")

Replace that with:

done < <(echo -n "$string")

Upvotes: 0

Related Questions