Home > other >  How to iterate over certain lines to match with GNU sed?
How to iterate over certain lines to match with GNU sed?

Time:07-09

The following code snippet gives the following error

sed: -e expression #1, char 45: unterminated address regex

when line number is iterated over:

for line in `seq 1 3 265`; do
  sed -i '\${\line\}s/foo/bar/' $FILE
done

Does anyone know how to fix this?

CodePudding user response:

A couple issues with current code:

  • sed script must use double quotes in order for bash variables to be expanded
  • no need for escape character (\) ... in this case

A couple small changes to OP's current code:

for line in `seq 1 3 265`; do
  sed -i "${line} s/foo/bar/" $FILE
done

One awk idea that requires a single pass through the input file:

awk '
BEGIN      { for (i=1;i<=265;i=i 3) seq[i] }
FNR in seq { $0=gensub(/foo/,"bar",1) }
1' $FILE

If using GNU awk, and satisfied with the results of this code, replace awk '... with awk -i inplace '... to facilitate updating the source file.

CodePudding user response:

you can do the seq 1 3 265 skip-count thing without any modulo % math at all :

jot -w '%d=foobar=barfool=' 265 | 

{m,g}awk 'BEGIN { __ =_^=  FS = "^$"
          __ =_ _ } NR !=_ || -sub("foo","bar")<(_ =(_<265)*__)' 

1=barbar=barfool=

2=foobar=barfool=
3=foobar=barfool=

4=barbar=barfool=

5=foobar=barfool=
6=foobar=barfool=

7=barbar=barfool=

8=foobar=barfool=
9=foobar=barfool=
.
.
.`

CodePudding user response:

This might work for you (GNU sed):

sed -i '1~3s/foo/bar;265{:a;n;ba}' file

From line 1 and every 3 lines thereafter until line 265 substitute foo for bar.

  • Related