Bash - 将文本文件剪切成列,切割字符串并将值存储到数组中

时间:2015-11-08 00:53:57

标签: arrays bash multiple-columns slice

我想对一些代码提出一些建议。

我想写一个小脚本,它将采用这种格式的输入文件

$cat filename.txt

111222233334444555666661112222AAAA
2222333445556612323244455445454545
2334556345643534505435345353453453

(依此类推)

它将被称为:script inputfile X(其中X是你想要做的切片数)

我希望脚本读取文件并根据用户输入对切片进行列化,即如果他为第一个切片提供输入1,2,为第二个切片提供3,4,则输出将如下所示:

#Here the first slice starts on the second digit, and length = 2 digits
#Here the second slice starts on the 3th digit and legth=4 digits



111 1222
222 2333
233 3455

这是我到目前为止所做的,但我只是将第一个切片的输出排成一行,有什么建议吗?

$./columncut filename.txt 2

#Initialize arrays
for ((i=1 ; i <= $2; i++)); do
        echo "Enter starting digit of $i string"; read a[i]
        echo "Enter length in digits of $i string"; read b[i]
done 

#Skim through file, slice strings

while read line
do
            for i in "${!a[@]}"; do
            str[i]=${line:${a[i]}:${b[i]}}
            done

            for i in "${!str[@]}"; do
            echo -n "$i "
            done


done <$1

我不知道是否有更容易做这样的工作,也许用awk?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

#usage: bash slice.sh d.txt "1-2" "4-8" "10-20"  
#column postions 1-2, 4-8 and 10-20 printed.  
#Note that it is not length but col position.   

inf=$1 # source file  
shift  # arg1 is used up for file discard it.  
while read -r line  
do
    for fmt    #iterate over the arguments  
    do
        slice=`echo $line | cut -c $fmt`  # generate one slice  
        echo -n "$slice  "       # oupt with two blanks, but no newline  
    done
    echo ""  # Now give the newline                     
done < "$inf"

示例运行: bash slice.sh d.txt&#34; 1-2&#34; &#34; 4-8&#34; &#34; 10-15&#34; 11 22223 334444
22 23334 555661
23 45563 564353

将所有这些生成的切片存储在数组中可能并不是很困难。