1

Despite the many similar questions, I am still confused.

qx|o1|md|4SAK9H7DQ876CAJ943,SJT8642H2DKT2CQ76,SQ5HKT653DAJCKT52|rh||ah|Board 1|sv|0|pg||
qx|o2|md|4SKQJ7642H9DQJ8CK8,STHAK8762D74CQJ65,SA85HQJTDAK96CT92|rh||ah|Board 2|sv|0|pg||
qx|o3|md|4ST3HAT9DAK96CA983,S76HK864D732CJT74,SAQJ82HJDQJT85CKQ|rh||ah|Board 3|sv|0|pg||
qx|o4|md|4SAQ4HT65432DAJ4CJ,SJT765HAKDT982C43,SK98HQJ9DK75CAQ92|rh||ah|Board 4|sv|0|pg||

In the above text, how do I find the every second occurrence of 4S, and replace it with 3S? (Or, in every other line, 4S becomes 3S.) (It is a given that the string 4S occurs only once in every line.) I working in Sublime Text, or Notepad++ on Windows.

3
  • 2
    What have you tried? Where are you stuck? What happens with your search? What program are you using?
    – Mokubai
    Apr 20, 2020 at 7:58
  • In case any Linux user appears with a similar problem: sed '2~2 s/4S/3S/' <datafile Apr 20, 2020 at 8:36
  • @Kamil Thanks, even that will do. (via sed.js.org)
    – blackened
    Apr 20, 2020 at 8:45

2 Answers 2

3

Using Notepad++:

  • Ctrl+H
  • Find what: .*?4S.*?\K4S
  • Replace with: 3S
  • CHECK Match case
  • CHECK Wrap around
  • CHECK Regular expression
  • CHECK . matches newline
  • Replace all

Explanation:

.*?         # 0 or more any character, not greedy
4S          # literally 4S, first one
.*?         # 0 or more any character, not greedy
\K          # forget all we have seen until this position
4S          # literally 4S, second one

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

0

I guess you'll need something like sed or awk to pull that off. On a Bash shell in Linux I'd use sed with the following commads:

sed -e 'N; s/4s/3s/2' < file.txt

whereby file.txt should contain your input lines.

When started, sed will
- pull the first line into the pattern space of sed,
- N will pull the next (second) line into the pattern space and
- `s/4s/3s/2' will then replace the second occurrence of "4s" in the pattern space with "3s".
After that the two lines are written to the standard output and a new cycle of sed begins.

Obviously, you also can pipe the output of a previous command through that.

'command' | sed -e 'N; s/4s/3s/2'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .