ntakouris
ntakouris

Reputation: 958

Replace Nth match of regex with sed

I've got a dataset that looks like:

1099511629352|Nunez|Jorge|female|17/11/2000|2011-04-04T05:54:52.693+0000|201.221.59.59|Opera|Facebook

Column separator in this case is | -> I want to replace the Nth column ($pos) given one row's id, using sed.

Here's what I've come up with now:

So the appropriate sed command would be:

sed "/^$id/[$columnsep]*[a-zA-Z0-9./\-:+]+/$columnsep$editvalue/$pos}" $file

I get [a- ...": invalid command code [ although it works with online regex testers like https://regexr.com/

Upvotes: 0

Views: 210

Answers (1)

oguz ismail
oguz ismail

Reputation: 50775

Something like this will do the job unless $columnsep is longer than one character.

sed "/^$id/s/[$columnsep]*[^$columnsep]*/$columnsep$editvalue/$pos" "$file"

But, I suggest using awk for tasks like this

awk -F "$columnsep" -v OFS="$columnsep" -v id="$id" -v editvalue="$editvalue" -v pos="$pos" '
  ($1==id){$pos=editvalue}1' "$file"

Upvotes: 1

Related Questions