【问题标题】:Bash - cut a text file into columns, slice strings and store value into arraysBash - 将文本文件切割成列,分割字符串并将值存储到数组中
【发布时间】:2015-11-08 00:53:57
【问题描述】:

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

我想写一个小脚本来接受这种格式的输入文件

$cat filename.txt

111222233334444555666661112222AAAA
2222333445556612323244455445454545
2334556345643534505435345353453453

(等等)

它将被称为:脚本输入文件 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?任何帮助将不胜感激。

【问题讨论】:

  • 我想用 bash 编码,不是出于任何奇怪的偏好,只是我被要求做的事情。
  • 你应该把bash作为标签。没有这个,你的 Q 看起来就像与语言无关并且没有人想回答。
  • 看不懂输入输出的对应关系。描述完全不清楚。
  • 请添加一个命令来演示所需的参数以及您希望将它们传递给脚本的方式。
  • 脚本将被调用为: ./script filename number 该数字表示我们希望在文件名的每一行上执行的切片数量。在示例输入/输出中,脚本被称为:./script filename 2

标签: arrays bash multiple-columns slice


【解决方案1】:
#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 "1-2" "4-8" "10-15" 11 22223 334444
22 23334 555661
23 45563 564353

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

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 2023-01-10
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    相关资源
    最近更新 更多