Shell tricks - Programming On Unix

Users browsing this thread: 1 Guest(s)
josuah
Long time nixers
There are the Rich's sh (POSIX shell) tricks. And now we have Nixers' sh tricks.

Replacing A with B in text

As simple as it may sound, there is not a lot of ways to do this, as quite every tool is oriented toward regexes. There is no -F flag in sed!

The only two ways I know is through parameter expansion and sed:

- Parameter expansion

Code:
text='original [text] [text]'
change='[text]'
into='text'

# do the changes one by one in a loop.  yeah, that's slow
while [ -z "${text##*"$change"*}" ]
do text=${text%%"$change"*}$into${text#*"$change"}
done

printf '%s\n' "$text"

Quite a bit complex! As I am aware of, the quotes expansion occurs it 2 context: while executing commands (so required in printf '%s\n' "$text") and in parameter extensions (so required in the ugly ${text%%"$change"*}).

- Sed <3

I can't remember where I did see that (link to the source appreciated), but it is a lot simpler than what I saw.

Code:
text='original [text] [text]'
change=$(printf '[text]' | sed 's/./[&]/g')
into=$(printf 'text' | sed 's/[&/\]/\\&/g')
printf '%s\n' "$text" | sed "s/$change/$into/g"

This is quite as lengthy, but less black magic is involved: put every character from the pattern in its own character class:

change became [[][t][e][x][t][]]
Therefore, even the '[' and ']' are interpreted as plain characters an not as part of a regex.


Messages In This Thread
Shell tricks - by josuah - 13-11-2017, 05:27 AM
RE: Shell tricks - by josuah - 13-11-2017, 05:39 AM
RE: Shell tricks - by venam - 14-11-2017, 01:53 AM
RE: Shell tricks - by josuah - 23-11-2017, 07:59 AM
RE: Shell tricks - by josuah - 23-11-2017, 08:52 AM
RE: Shell tricks - by josuah - 04-12-2017, 07:43 AM
RE: Shell tricks - by z3bra - 04-12-2017, 08:11 PM
RE: Shell tricks - by josuah - 05-12-2017, 08:07 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:02 AM
RE: Shell tricks - by josuah - 05-12-2017, 09:08 AM
RE: Shell tricks - by josuah - 08-12-2017, 12:25 PM