应 Charles Duffy 的要求以更窄的焦点重新创建此内容。
我有一个如下所示的 CSV 文件:
Security Policy: Blahblahblah,,,,,,,,,
12,,host_A,net-B,https,drop,Log,Any,Any,comments
13,,host_A,net-B,smtp,drop,Log,Any,Any,comments
14,,host_A,net-B,http,accept,Log,Any,Any,comments
,,net-C,,,,,,,
,,net-D,,,,,,,
15,,host_A,net-B,http,accept,Log,Any,Any,comments
,,host_B,net-C,service_X,,,,,
,,host_C,net-D,service_y,,,,,
,,host_D,,,,,,,
,,host_E,,,,,,,
我需要分别解析每个值,但是我需要在它们各自的语句中包含 $1。如您所见,这对 13 岁和 14 岁的 child 来说很容易,但是当他们的列为空白( child )时,这对 14 岁和 15 岁的 child 来说就成了一个严重的问题。
遍历这个的最佳方法是什么?
例如,我希望输出如下所示:
'text goes here' $1 'more text' $3 'more text'
'text goes here' $1 'more text' $4 'more text'
等等
使用实数值(15):
'text goes here' 15 'more text' host_A 'more text'
'text goes here' 15 'more text' host_B 'more text'
'text goes here' 15 'more text' host_C 'more text'
'text goes here' 15 'more text' host_D 'more text'
'text goes here' 15 'more text' host_E 'more text'
'text goes here' 15 'other text' net-B 'more text'
'text goes here' 15 'other text' net-C 'more text'
'text goes here' 15 'other text' net-D 'more text'
'text goes here' 15 'text' http 'more text'
'text goes here' 15 'text' service_X 'more text'
'text goes here' 15 'text' service_y'more text'
等等等等。
谢谢,
最佳答案
process_file() {
# declare local variables
declare -a last_seen row
declare col_idx col
read # discard first line
while IFS=, read -r -a row; do
# for each remaining line...
for col_idx in "${!row[@]}"; do
# update last-seen rows with any contents here
col=${row[$col_idx]}
if [[ $col ]]; then
last_seen[$col_idx]=$col
fi
done
# ...and operate on those values.
printf 'text goes here %s more text %s more text\n' \
"${last_seen[0]}" "${last_seen[2]}" "${last_seen[3]}"
done
}
process_file <input.csv >output.txt
关于linux - Awk/sed Loop over CSV - 将 child 绑定(bind)到第 1 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15792613/