[英]Awk/sed Loop over CSV - tie children to column 1
應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來說這很容易,但是當它們的列是空白的(兒童)時它會成為14和15的嚴重問題。
循環使用它的最佳方法是什么?
例如,我希望輸出看起來像:
'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
我真的在猜測,因為你的問題不能解釋你想要什么,但是你正在尋找的是這樣的東西:
$ cat file
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,,,,,,,
$ awk -f tst.awk file
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
14 net-C net-B http accept Log Any Any comments
14 net-D net-B http accept Log Any Any comments
15 host_A net-B http accept Log Any Any comments
15 host_B net-C service_X accept Log Any Any comments
15 host_C net-D service_y accept Log Any Any comments
15 host_D net-B http accept Log Any Any comments
15 host_E net-B http accept Log Any Any comments
$ cat tst.awk
BEGIN{ FS="," }
NR==1 { next }
$1 != "" { split($0,dflt) }
{ for (i=1;i<=NF;i++) if ($i == "") $i = dflt[i]; print }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.