I have a variable, e.g. a'b
, containing a single quote which I need to replace by two single quotes before writing it to a file: a''b
.
The following bash code used to get the job done for me ...
line="a'b"
echo "${line//\'/\'\'}" > out.txt
... until today when I discovered diverging outputs depending on the version of bash being used:
- GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu):
a''b
- GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu):
a\'\'b
I tried to modify the line above in numerous ways but was unable to have it produce the same output a''b
in both bash shells.
I ended up using a combination of echo
and sed
instead,
echo "$(echo $line | sed "s/'/''/g")" > out.txt
but I am still wondering if the job can be gotten done with a more concise pure bash expression. Can it?
printf "%s\n" $line | sed "s/'/''/g" > out.txt
will do. BTW, theecho "${line//\'/\'\'}"
works as desired in bash 5.0.3 for me. – cas Aug 28 '19 at 08:58printf
. – pLumo Aug 28 '19 at 08:58ls
? if so then a) don't do that and b) runman ls
and search for--quoting-style
and c) runtypeset -p QUOTING_STYLE
and d) see Why is 'ls' suddenly wrapping items with spaces in single quotes? – cas Aug 28 '19 at 09:02ls
, then this is an XY Problem for at least two reasons. Firstly because there are many better ways to process a list of files than to parse ls. Secondly because the need to double any single-quotes probably only arises because you're trying to parse the output ofls
and then (presumably) use the filenames as arguments to some other program. What are you actually trying to achieve that you think parsing ls is part of the solution for? – cas Aug 28 '19 at 09:09printf
call with anecho
call by now. Edited the question this way too. – Bastian Aug 28 '19 at 09:21git diff -U0 --no-prefix --no-color --ignore-space-at-eol -b -w ${IN_DIR}
– Bastian Aug 28 '19 at 09:23echo " write(*,*) '$(echo "${line}" | sed "s/'/''/g")'" >> ${OUT_FILE}
– Bastian Aug 28 '19 at 09:24