首页 > 解决方案 > 替换字符串并在同一字段的某个位置插入一个字符

问题描述

嗨,我正在尝试替换\_\_SEC\_\_00并在该特定字段中的 19 个字符之后$6$插入一个。$

数据:

Avivit Katzir,avivit,\_\_SEC\_\_00wLaxAKg1ecw80jGW0ACTr.kI5gttGo/YxHHUOeCZzDn8.3yFyPqJSKwXXYfBVPjco7RKPjK/1XBvYQAXC4jKm9pt8G6WtMrIRs0Lp/,demo,demo,demo

预期输出:

Avivit Katzir,avivit,$6$wLaxAKg1ecw80jGW$0ACTr.kI5gttGo/YxHHUOeCZzDn8.3yFyPqJSKwXXYfBVPjco7RKPjK/1XBvYQAXC4jKm9pt8G6WtMrIRs0Lp/,demo,demo,demo

我试过这个命令:

sed -e 's/\\_\\_SEC\\_\\_../\$6\$/' -e 's/./&\$/19'

但是我在插入时遇到了问题$

标签: awksed

解决方案


awk中,根据您用 GNU 编写的示例,您能否尝试以下示例awk\\_\\_SEC\\_\\_00如果您想\\_\\_SEC\\_\\_..在此处匹配任何字符,您可以从更改为。

awk '
match($0,/\\_\\_SEC\\_\\_00/){
  print substr($0,1,RSTART-1) "$6$"\
  substr($0,RSTART+RLENGTH,16)"$"\
  substr($0,RSTART+RLENGTH+16)
}' Input_file

说明:为上述添加详细说明。

awk '                                  ##Starting awk program from here.
match($0,/\\_\\_SEC\\_\\_00/){         ##using match function of awk here to match regexp \\_\\_SEC\\_\\_00, notice double \\ to escape \ here.
  print substr($0,1,RSTART-1) "$6$"\   ##Printing sub string from 1st index of line to just before 1 index of matched pattern then printing $6$
  substr($0,RSTART+RLENGTH,16)"$"\     ##Printing sub string after matched part till next 16 characters here thne printing $ here.
  substr($0,RSTART+RLENGTH+16)         ##Printing rest of the line from here.
}' Input_file                          ##mentioning Input_file here.

推荐阅读