簡體   English   中英

Bash:“printf%q $ str”在腳本中刪除空格。 (備擇方案?)

[英]Bash: “printf %q $str” deletes spaces when in scripts. (Alternatives?)

printf%q應該引用一個字符串。 但是,當執行到腳本中時,它會刪除空格。

這個命令:

printf %q "hello world"

輸出:

hello\ world

哪個是對的。

這個腳本:

#!/bin/bash

str="hello world"
printf %q $str

輸出:

helloworld

這是錯的。

如果確實需要這樣的行為,那么在腳本中有什么替代方法可以引用包含任何字符的字符串,以便可以通過被調用的程序將其轉換回原始字符?

謝謝。

軟件:GNU bash,版本4.1.5(1)-release(i486-pc-linux-gnu)

編輯:解決了,謝謝。

你應該使用:

printf %q "$str"

例:

susam@nifty:~$ cat a.sh
#!/bin/bash

str="hello world"
printf %q "$str"
susam@nifty:~$ ./a.sh 
hello\ world

當您運行printf %q $str ,shell會將其擴展為:

printf %q hello world

因此,字符串helloworld作為printf命令的兩個獨立參數提供,它並排打印兩個參數。

但是當你運行printf %q "$str" ,shell會將其擴展為:

printf %q "hello world"

在這種情況下,字符串hello world作為printf命令的單個參數提供。 這就是你想要的。

以下是您可以嘗試使用這些概念的內容:

susam@nifty:~$ showargs() { echo "COUNT: $#"; printf "ARG: %s\n" "$@"; }
susam@nifty:~$ showargs hello world
COUNT: 2
ARG: hello
ARG: world
susam@nifty:~$ showargs "hello world"
COUNT: 1
ARG: hello world
susam@nifty:~$ showargs "hello world" "bye world"
COUNT: 2
ARG: hello world
ARG: bye world
susam@nifty:~$ str="hello world"
susam@nifty:~$ showargs $str
COUNT: 2
ARG: hello
ARG: world
susam@nifty:~$ showargs "$str"
COUNT: 1
ARG: hello world

嘗試

printf %q "${str}"

在你的腳本中。

這對我有用。 滿足這些要求

  1. 接受可能包含shell特殊字符的任意輸入
  2. 不輸出轉義字符,“\\”
#! /bin/bash

FOO='myTest3$;  t%^&;frog now! and *()"'

FOO=`printf "%q" "$FOO"`                        # Has \ chars
echo $FOO

# Eat all the \ chars
FOO=$(printf "%q" "$FOO" | sed "s/\\\\//g")     # Strip \ chars

echo $FOO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM