Home > Mobile >  How to replace a pattern for all occurrences after a given line using Bash?
How to replace a pattern for all occurrences after a given line using Bash?

Time:01-12

I have been using sed -i "" "s/pattern/replacement/g" file.txt to replace pattern all over my file, but my goal is to do it for all the occurrences after the third line. I managed to do it using,

sed -n -e '3,$p' file.txt > aux
cat aux | sed "s/pattern/replacement/gI" > file.txt ,

but I'm wondering if there is a faster way to do it, preferably without using an auxiliary file (aux).

CodePudding user response:

You can use the "address range" before the substitution:

sed -e '3,$ s/pattern/replacement/gI'

If you want to remove the first two lines, you can use tail

sed ... | tail -n  3

or you can tell sed to remove them:

sed -e '1,2d' -e '3,$ s/pattern/replacement/gI'
  •  Tags:  
  • Related