遍历每行和文件中的每个字符

时间:2013-11-29 12:26:30

标签: bash unix

我正在尝试获取文件名和字符索引,并从每行打印带有该索引的字符(如果存在这样的字符,则为用户输入的每个字符索引执行此操作)。 这是我的代码:

#!/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

但是,它说错误:

line 20: abcdefgh: No such file or directory

第20行是最后一个done,所以它无法帮助我找出错误的位置。

那么我的代码有什么问题,我该如何解决?

非常感谢。

3 个答案:

答案 0 :(得分:2)

我认为“削减”可能适合该法案:

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

答案 1 :(得分:0)

这条线似乎有问题:

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

将其替换为:

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

答案 2 :(得分:0)

替换

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

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

它也是如此,但允许避免此类错误。

另一种方法是使用cut

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

它可以替换两个内部循环

相关问题