我输入文件的结构如下:
<string1> <string2> <stringN>
hello nice world
one three
注意:,第二行在第二列上有一个tab / null。所以第二行的第二列是空的,而不是“三”
在 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]: ''
基本上我所做的是遍历输入文件(此处作为参数传递),执行所有&#34;清理&#34;比如防止修剪空格,忽略反斜杠也考虑最后一行。 然后我更换标签&#39; \ t&#39;用逗号 最后将该行读入一个数组(列),以便能够选择一个特定的列。
输入文件有选项卡作为分隔符值,所以我尝试将其转换为csv格式,我不确定我使用的正则表达式是否在bash中是正确的,或者其他错误,因为这不会返回值阵列。
由于
答案 0 :(得分:0)
你几乎就在那里,稍微修改一下翻译&#39; \ t&#39;到逗号,您还必须将 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'