-2

and thanks in advance. I have a huge database where all lines start like this:

(497, 36390, 495, 88, 89, 2, 'xxdurango/a-...

(498, 36391, 1, 93, 100, 1, 'xxsalamanca...

(499, 36392, 498, 94, 95, 2, 'xxsalamanca/noti...

(500, 36393, 498, 96, 97, 2, 'xxsalama...

(501, 36394, 1, 101, 108, 1, 'xxg...

I need to change the third column after (#, #,

I am trying to use grep <.,.,> <(.,.,>

all this grep commands select other values in the lines.

I want to make a search and replace (using BBEdit), all of the third column needs to change to the same value.

Need to search for: begining of line,+ numeral1 (,) numeral2(,)

Or something like: begining of line, 3digit number (,) four digit number (,)

Any hint?

thanks

4

1 回答 1

0

的使用grep只能显示与您想要的模式匹配的行,因此您得到全有或全无,您将无法获得所需的字段分隔。还有其他工具可以使这变得更容易,例如,sed它使用类似的正则表达式但可以编辑流(它的名称是Stream Editor的缩写。例如,以下会将第三个字段更改为 YYYY:

sed -r 's/^(\(([^,]+,){2})[^,]+,/\1 YYYY,/p' input_filename

该命令分解如下:

  • -r打开扩展正则表达式
  • s/是搜索和替换命令的开始
  • ^在行首锚定搜索
  • (开始一个我们稍后会提到的分组
  • \(是行首的文字左括号
  • ([^,]+,)读取为一个或多个非逗号后跟逗号的字符,并将其视为一个单元
  • {2}表示前一个单元重复了两次
  • )将整个模式关闭到这一点,作为一个组,稍后会提到
  • [^,]+,同上,非逗号后跟逗号
  • /标记从搜索模式到替换的变化
  • \1被模式空间中的第一组替换(直到第二个逗号)
  • YYYY是我们的字面替换
  • /p结束替换模式并说打印出更改

使用类似的东西awk会更容易:

awk -F, '{OFS=","; $3="YYYY"; print}' input_filename

应该很明显这是如何工作的,您可能只需要知道-F,将输入字段分隔符设置为 ,并且OFS=","对 print 使用的输出字段分隔符执行相同操作。请注意,我们只是使用逗号来分隔字段,因此第一个字段将包含左括号。由于您只想更改第三个字段,因此这不是问题。如果您想更改第一个字段,则需要考虑到这一点。

另一种选择是使用cutand paste,但我将把它留作练习。

于 2017-04-05T06:42:23.473 回答