【问题标题】:Bash - Looping through the content of file and perform actions on rows and columnsBash - 遍历文件的内容并对行和列执行操作
【发布时间】:2017-08-21 21:00:13
【问题描述】:

我的输入文件的结构如下:

<string1>   <string2>   <stringN> 
hello   nice    world  
one     three

注意:,第二行的第二列有一个制表符/空值。所以第二行的第二列是空的,而不是“三”

bash 中,我想遍历每一行并且还能够处理每一列(字符串 [1-N])

我可以迭代每一行:

#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
        line=${line/$/'\t'/,}
        read -r -a columns <<< "$line"
        echo "current Row: $line" 
        echo "column[1]: '${columns[1]}'"
        #echo "column[N] '${columns[N]}'"       
done < "${1}"

预期结果

current Row: hello,nice,world 
column[1]: 'nice'
current Row: one,,three
column[1]: ''

基本上我所做的是遍历输入文件(这里作为参数传递),执行所有“清理”,例如防止空格被修剪,忽略反斜杠并考虑最后一行。 然后我用逗号替换标签“\ t” 最后将该行读入一个数组(列),以便能够选择特定的列。

输入文件有制表符作为分隔值,所以我尝试将其转换为 csv 格式,我不确定我使用的正则表达式在 bash 中是否正确,或者其他错误,因为这不会在数组。

谢谢

【问题讨论】:

    标签: arrays regex bash csv


    【解决方案1】:

    你快到了,在将 '\t' 翻译成 逗号 的问题上稍作修正,你还必须将 IFS 设置为逗号。

    试试这个:

    #!/bin/bash
    while IFS='' read -r line || [[ -n "$line" ]]; do
            line=${line//$'\t'/,}
            IFS=',' read -r -a columns <<< "$line"
            #echo "current Row: $line" 
            echo "column[0]:'${columns[0]}' column[1]:'${columns[1]}' column[2]:'${columns[2]}'"
    
    done < "${1}"
    

    运行:

    $> <the_script> <the_file>
    

    输出

    column[0]:'hello' column[1]:'nice' column[2]:'world '
    column[0]:'one' column[1]:'' column[2]:'three'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 2013-12-14
      • 2014-02-05
      • 1970-01-01
      • 2017-10-27
      • 2014-04-25
      相关资源
      最近更新 更多