Sunday, March 13, 2022

[SOLVED] Replacing line of text cointing using sed

Issue

's/document\.querySelector\(\'\.popup\'\)\.classList\.add\(\'active\'\)/document\.querySelector\(\'\.popup\'\)\.classList\.add\(\'noactive\'\)/' design.js

I'm trying to replace document.querySelector('.popup').classList.add('active') by document.querySelector('.popup').classList.add('noactive')


Solution

You can use

#!/bin/bash
s="document.querySelector('.popup').classList.add('active')"
sed "s/\\(document\\.querySelector('\\.popup')\\.classList\\.add('\\)\\(active')\\)/\1no\2/g" <<< "$s"
# => document.querySelector('.popup').classList.add('noactive')

See the online demo. The regex is POSIX BRE compliant and matches

  • \(document\.querySelector('\.popup')\.classList\.add('\) - Group 1 (\1): a literal document.querySelector('.popup').classList.add(' text
  • \(active')\) - Group 2 (\2): a literal active') text.

Note the capturing groups in a POSIX BRE regex are set with \(...\). The literal dots need escaping and since the double quoted literal is used, the backslashes are doubled (and no need to escape single quotes).



Answered By - Wiktor Stribiżew
Answer Checked By - Marie Seifert (WPSolving Admin)