简体   繁体   English

Bash%s格式说明符消除了打印输出时字符串中的空格

[英]Bash %s format specifier eliminates spaces in string on print out

I am starting to use the printf instead of echo . 我开始使用printf代替echo My first forray into printf %s is this: 我对printf %s第一次追求是:

#!/bin/bash
danny=$(tail -1 /come/and/play/with/US.log| ~/walt/convert_gm_est)
printf "%s" $danny
08:02.020ZINFO<-casper/casperbox001wowSYSSTATS[sz=21,tag=0,aux=0]process_log2221397800

It eliminates all the spaces in the string. 它消除了字符串中的所有空格。 So I added a space after the format specifier. 因此,我在格式说明符后面添加了一个空格。 the string looks nicer with the spaces plus I could rip out the time with awk very easily. 字符串在空格处看起来更好,而且我可以很轻松地用awk抽出时间。 I don't see anything about this on the interwebs. 我在互联网上什么都没有看到。 I tried a "%s\\s" and that did not work. 我尝试了"%s\\s" ,但没有成功。 Is this standard procedure for using format specifiers - use a space after %s ? 这是使用格式说明符的标准过程吗?在%s后使用空格吗? Is this the way to do it or am I missing something? 这是这样做的方式还是我错过了什么?

#!/bin/bash
danny=$(tail -1 /come/and/play/with/US.log| ~/walt/convert_gm_est)
printf "%s " $danny
08:02.020Z INFO <- casper/casperbox001wow SYSSTATS[sz=21, tag=0, aux=0] process_log 2221397 80 0 casper@casperbox001wow:~$

When the shell evaluates: 当外壳评估时:

printf "%s" $danny

the shell will expand the value of the variable danny and then split it into words. shell将扩展变量danny的值,然后将其拆分为单词。 It will also expand globs in those words. 它还会扩大这些词的范围。 Once that is done, the expression will look something like this (quotes added for clarification): 完成后,该表达式将类似于以下内容(添加了引号以进行说明):

printf '%s' '08:02.020Z' 'INFO' '<-' 'casper/casperbox001' 'wow0' 'SYSSTATS'...

printf repeats its format string until all of the arguments are consumed. printf重复其格式字符串,直到使用完所有参数为止。 So using the format string %s causes the arguments to be concatenated without intervening spaces. 因此,使用格式字符串%s会导致参数串联而不会插入空格。

You probably meant to quote $danny so that it would be presented as a single argument to printf: 您可能想要引用$danny以便将其作为单个参数提供给printf:

printf "%s" "$danny"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM