linux - 使用 printf 如何转义 shell 脚本中的特殊字符?

标签 linux bash shell printf

我正在尝试在 shell 中使用 printf 格式化字符串,我将从文件中获取输入字符串,该字符串具有特殊字符,如 %,',"",,\user,\tan

如何转义输入字符串中的特殊字符?

例如

#!/bin/bash
# 

string='';
function GET_LINES() {

   string+="The path to K:\Users\ca, this is good";
   string+="\n";
   string+="The second line";
   string+="\t";
   string+="123"
   string+="\n";
   string+="It also has to be 100% nice than %99";

   printf "$string";

}

GET_LINES;

我希望这会以我想要的格式打印

The path to K:\Users\ca, this is good
The second line   123
It also has to be 100% nice than %99

但它给出了意想不到的结果

./script: line 14: printf: missing unicode digit for \U
The path to K:\Users\ca, this is good
The second line 123
./script: line 14: printf: `%99': missing format character
It also has to be 100ice than 

那么我怎样才能在打印时去掉特殊字符呢? echo -e 也有问题。

最佳答案

尝试

printf "%s\n" "$string"

参见 printf(1)

关于linux - 使用 printf 如何转义 shell 脚本中的特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25958430/

相关文章:

php - 通路不适用于 pdftk

linux - Bash enter & ctrl-z 按键

bash - 找不到 ZSH 命令,即使命令在我的 $PATH 中

bash - 如何grep最后一次出现的线型

linux - 从 block 中删除一行

linux - 将参数从 shell 脚本传递给 awk

linux - 如何逐行读取文本文件并按字符拆分行?

linux - 当我在 Linux 中的项目目录上运行 make 命令时,出现以下错误

linux - 如何将密码添加到 scp 命令的脚本中

linux - 使用 sh 命令运行时替换 myscript.sh 文件中的变量值