Shox88
Shox88

Reputation: 67

sed find and replace string surrounded by [] output to file

Have a file with the following

"SCAN_IN[0]" : input;

Want to use sed to find and replace with scan_0

I am using the following command

sed  's/SCAN_IN[]0[]/scan_0/' fileA > fileB

This is what i am getting

"scan_00]" : input;

I want

"scan_0" : input;

Upvotes: 1

Views: 55

Answers (2)

user5683823
user5683823

Reputation:

I will make a few assumptions:

You want "SCAN_IN[?]" to be replaced with "scan_?" where ? may be any string of (zero or more) consecutive non-closing-bracket characters. This means three things (at least): that you must convert from upper-case in the input to lower-case in the output (which is pretty odd); that the double-quotes are part of the matching pattern - so that only SCAN_IN is matched, but not for example RESCAN_IN; and that you want this done for anything within brackets, not just for the single character 0.

Also, you don't care where the pattern appears (whether it's before additional text like : input or anywhere else), and you must make the same change even if the pattern appears more than once on the same line. (So we need the g flag.)

The sed command that can do all that is:

sed -E 's/"SCAN_IN\[([^]]+)]"/"scan_\1"/g'

Here are a few examples:

$ echo '"SCAN_IN[0]" : input' | sed -E 's/"SCAN_IN\[([^]]*)]"/"scan_\1"/g'

"scan_0" : input


$ echo '"TO_SCAN_IN[0]" : input' | sed -E 's/"SCAN_IN\[([^]]*)]"/"scan_\1"/g'

"TO_SCAN_IN[0]" : input



$ echo '"SCAN_IN[0]" : input "RESCAN_IN[1]" "SCAN_IN[37]" "SCAN[0]"' | 
                                 sed -E 's/"SCAN_IN\[([^]]+)]"/"scan_\1"/g'

"scan_0" : input "RESCAN_IN[1]" "scan_37" "SCAN[0]"

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627128

The SCAN_IN[]0[] pattern matches SCAN_IN first and then []0[] matches one char: either ], or 0, or [ (due to "smart placement" when the unescaped ] located right after the opening bracket expression [ (or [^ is it is a negated bracket expression) is treated as a literal ] and not the closing bracket expression char).

In your string, SCAN_IN[]0[] matches SCAN_IN[ and thus the result of the replacement is scan_00]" : input;.

You may use

sed 's/SCAN_IN\[0]/scan_0/' fileA > fileB

See the online sed demo:

s='"SCAN_IN[0]" : input;'
sed 's/SCAN_IN\[0]/scan_0/'  <<< "$s"
# => "scan_0" : input;

Upvotes: 1

Related Questions