help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

string escaping in bash


From: Peng Yu
Subject: string escaping in bash
Date: Fri, 12 Mar 2021 09:05:23 -0600

Hi,

I wondering if there is a simple but robust way to implement string escaping.

Specifically, the string "\n" (a slash and the letter "n") should be
replaced as a newline character, the string "\t" (a slash and the
letter "t") should be replaced as a tab character, and "\\" (two
consecutive slashes should be replaced with a single slash. All other
characters and their preceding slash (if there is) should remain as
is.

If I use a multi-string-replacement strategy, it will not be robust.
For example, if I do it in the order 1) \\ -> \, 2) \n -> newline, \\n
will not be replaced correctly. The result should be "\n" (a slash
followed by the letter "n").

$ x='\\n'; x=${x//\\\\/\\}; x=${x//\\n/$'\n'}; declare -p x
declare -- x="
"

Does anybody have a robust way to implement this in bash?

-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]