I wrote a BASH file that features multiple embedded loops of the form
for P in {'0.10','0.20', [...] '0.90','1.00'}; do
for Q in {'0.10','0.20', [...] ,'0.90','1.00'}; do
[...]
I use these variables both as parameters for a command line application, and to create file names directly in BASH. I would like to create duplicates, say $P_REP=0_10
that replaces the dot by an underscore without writting a explicit switch statement for every case, or some hardcoded equivalent. The (non-elegant way) I found to go about it is to
P,Q
to a temporary file.sed 's/./_/ -i
.Hence, I was wondering if it is possible to run a sed like command directly on the content of a variable?
The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.
'g' option is used in `sed` command to replace all occurrences of matching pattern. Create a text file named python.
By default sed does not overwrite the original file; it writes to stdout (hence the result can be redirected using the shell operator > as you showed).
Just use double quotes instead of single quotes. You'll also need to use {} to delimit the number_line variable correctly and escape the \ , too.
You can do pattern substitution directly in bash:
P_REP=${P/./_}
Q_REP=${Q/./_}
From the bash(1) man page:
Paramter Expansion
${parameter/pattern/string}
Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with
/
, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with#
, it must match at the beginning of the expanded value of parameter. If pattern begins with%
, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is@
or*
, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with@
or*
, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
John Kugelman's answer is fine for your example, but if you need to process the content of a variable with the actual sed program (or some other arbitrary command), you can do it like this:
P_REP=$(sed 's/\./_/' <<< "$P")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With