如果一行以 {condition} 开头,则在第 187 个字符后插入变量

如果一行以 {condition} 开头,则在第 187 个字符后插入变量

我有一个超过 10k 行的 .txt 文件。有些行以1,POS,MGC=或开头1,NEG,MGC=。对于这些行,我想在该行的第 187 个字符之后插入一个变量,同时保留后面的文本。

到目前为止我所拥有的是

awk 'BEGIN{FS=OFS=""}
{if (substr($0,1,10)~"1,...,MGC=")
$187=$variable} inputfile > outputfile

这根本不起作用。

答案1

使用sed

sed "/^1,\(POS\|NEG\),MGC=/ s/./\0$variable/187" file

.匹配任何字符,数字标志187将导致s/.../.../替换第 187 个匹配项。总之,这意味着第 187 个字符将被其自身替换,后跟 的值$variable

行距将此/pattern/操作限制为以“1,POS,MGC=”或“1,NEG,MGC=”开头的行。

答案2

使用perl:

perl -i.bak -spe 's/^(?=1,(POS|NEG),MGC=).{187}\K/$new/' -- -new="$text" file

测试

line=$(seq 63 | paste -sd,)
lines=( "$line" "1,POS,MGC=$line" "1,NEG,MGC=$line" "1,foo,MGC=$line" )
printf "%s\n" "${lines[@]}" | perl -spe 's/^(?=1,(?:POS|NEG),MGC=).{187}\K/$new/' -- -new="HELLO!"
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63
1,POS,MGC=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,HELLO!63
1,NEG,MGC=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,HELLO!63
1,foo,MGC=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63

答案3

尝试

awk -vINSVAR="$variable" '/1,(POS|NEG),MGC/ {$0 = substr ($0, 1, 187) INSVAR substr ($0, 188)} 1' file

相关内容