我有一個檔案0.txt,括號中包含以下值欄位內容:
(bread,milk,),
(rice,brand B,),
(pan,eggs,Brandc,),
我正在 OS 和其他地方尋找如何將字母添加x到逗號之間的每個值的開頭,以便我的輸出檔案變為(使用 bash unix):
(xbread,xmilk,),
(xrice,xbrand B,),
(xpan,xeggs,xBrand C,),
我真正嘗試過但還不夠的唯一一件事是:
awk '{gsub(/,/,",x");print}' 0.txt
出于所有目的,前綴不應應用于每行末尾的最后一個逗號。
uj5u.com熱心網友回復:
和 awk
awk 'BEGIN{FS=OFS=","}{$1="(x"substr($1,2);for(i=2;i<=NF-2;i ){$i="x"$i}}1'
解釋:
# Before you start, set the input and output delimiter
BEGIN{
FS=OFS=","
}
# The first field is special, the x has to be inserted
# after the opening (
$1="(x"substr($1,2)
# Prepend 'x' from field 2 until the previous to last field
for(i=2;i<=NF-2;i ){
$i="x"$i
}
# 1 is always true. awk will print in that case
1
uj5u.com熱心網友回復:
訣竅是錨定正則運算式,以便它匹配您要使用的整個以逗號結尾的子字串,而不僅僅是逗號(并避免語法中的其他“特殊”字符)。
awk '{ gsub(/[^,()] ,/, "x&") } 1' 0.txt
sed -r 's/([^,()] ,)/x\1/g' 0.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/333609.html
上一篇:BASH按版本排序檔案名
