我有一個由逗號分隔的幾個欄位組成的 CSV 檔案。
id,name,nationality,sex,date_of_birth,height,weight,sport,gold,silver,bronze,info
736041664,A Jesus Garcia,ESP,male,1969-10-17,1.72,64,athletics,0,0,0,
當“運動”列正在射擊或柔道時,我必須將“名稱”列上的值從小寫更改為大寫。我只能使用sed. 我正在使用這個命令
sed 's/\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\),\(.*\)/\1,\U\2\E,\3,\4,\5,\6,\7,\shooting|judo,\9,\10,\11,\12/' athletesv2.csv
但它不起作用,因為它只是在所有行中顯示“射擊|柔道”。
我怎樣才能進行這些替換?
請注意,輸出必須是 .sed 檔案,必須使用sed -f script.sed athletes.csv
在輸出中我需要保留標題。
我正在使用 Ubuntu Linux。
uj5u.com熱心網友回復:
如果您可以使用 GNU sed,則可以使用
rx='^([^,]*),([^,]*),([^,]*,[^,]*,[^,]*,[^,]*,[^,]*,(shooting|judo),[^,]*,[^,]*,[^,]*,[^,]*)$'
repl='\1,\U\2\E,\3'
sed -E "s/$rx/$repl/" athletes.csv
查看在線演示:
#!/bin/bash
rx='^([^,]*),([^,]*),([^,]*,[^,]*,[^,]*,[^,]*,[^,]*,(shooting|judo),[^,]*,[^,]*,[^,]*,[^,]*)$'
repl='\1,\U\2\E,\3'
s='id,name,nationality,sex,date_of_birth,height,weight,sport,gold,silver,bronze,info
736041664,A Jesus Garcia,ESP,male,1969-10-17,1.72,64,athletics,0,0,0,
132041664,A Jesus Garcia,ESP,male,1969-10-17,1.72,64,shooting,0,0,0,'
sed -E "s/$rx/$repl/" <<< "$s"
輸出:
id,name,nationality,sex,date_of_birth,height,weight,sport,gold,silver,bronze,info
736041664,A Jesus Garcia,ESP,male,1969-10-17,1.72,64,athletics,0,0,0,
132041664,A JESUS GARCIA,ESP,male,1969-10-17,1.72,64,shooting,0,0,0,
筆記:
^([^,]*),([^,]*),([^,]*,[^,]*,[^,]*,[^,]*,[^,]*,(shooting|judo),[^,]*,[^,]*,[^,]*,[^,]*)$是一個匹配整個字串的模式(^是字串的開頭并$匹配字串的結尾),它將欄位 1 和 2 捕獲到單獨的組中,并將字串的其余部分捕獲到組 3 中。欄位 8 模式是硬編碼的,(shooting|judo)要么匹配shooting或judo。\U\2\E在替換中會將第 2 組的值放回大寫。
請注意,您不能在 sed 中使用多個\9反向參考,因此您需要減少它們的數量并將那些未使用的組分組。
uj5u.com熱心網友回復:
使用sed
$ sed '/^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,shooting\|judo,/s/,[^,]*/\U&/' input_file
id,name,nationality,sex,date_of_birth,height,weight,sport,gold,silver,bronze,info
736041664,A JESUS GARCIA,ESP,male,1969-10-17,1.72,64,shooting,0,0,0,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457881.html
上一篇:無法在Ubuntu上升級離子版本
