English 中文(简体)
因此,湿度-结果为1
原标题:why wc -l result is 1 for empty variable
  • 时间:2024-02-24 09:55:36
  •  标签:
  • bash

鉴于以下双现金编码:

grep match_nothing file.txt | wc -l

结果0正确。 但以下法典

LINES=$(grep match_nothing file.txt)
wc -l <<< "$LINES"

回返 1. 为什么发生这种情况,我怎么能正确。

最新情况:

这个问题仅以<代码>grep为例。 混淆我的是,为什么把产出分配到一个变量,导致不同的结果。

问题回答

关于:

为什么发生这种情况

本文所述的目的是将插图转换成一个工具可以读成投入的工具,就像它读成一个文件,而根据《规则》第9条,一个有效的文本文件总是在一条线“Fed”上终结,因此,在座的建筑中增加了一条线“Fed”的结尾。 如果它不这样做,那么它的产出就不会成为一种有效的PPOSIX文本“档案”,因此,你可以可靠地将其用作任何文本处理工具(如ed、 a等)的投入。

关于:

以及我如何正确

这已经是正确的,但如果你不希望添加一条线,则使用代号为f的指挥替换来提供以下投入:

$ lines=  

$ wc -l <<< "$lines"
1

$ wc -l < <(printf  %s  "$lines")
0

而了解该产出后,则不构成PPOSIX和YMMV的有效文本文件,说明如何使用各种工具,例如,考虑到无豁免:

$ lines= foo 

典型的预期行为将通过以下方式提供:

$ wc -l <<< "$lines"
1

$ while IFS= read -r var; do echo "$var"; done <<< "$lines"
foo

在使用代号为的指令时,请参看。 也许不会是你所期望的:

$ wc -l < <(printf  %s  "$lines")
0

$ while IFS= read -r var; do echo "$var"; done < <(printf  %s  "$lines")
$

If you want to provide input that has a Line Feed added when the variable is populated but doesn t otherwise then you could consider something like:

$ lines=  

$ wc -l < <(printf  %s  "$lines"; (( ${#lines} )) && printf  
 )
0

$ while IFS= read -r var; do echo "$var"; done < <(printf  %s  "$lines"; (( ${#lines} )) && printf  
 )
$

$ lines= foo 

$ wc -l < <(printf  %s  "$lines"; (( ${#lines} )) && printf  
 )
1

$ while IFS= read -r var; do echo "$var"; done < <(printf  %s  "$lines"; (( ${#lines} )) && printf  
 )
foo




相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

Bash usage of vi or emacs

From a programming standpoint, when you set the bash shell to use vi or emacs via set -o vi or set -o emacs What is actually going on here? I ve been reading a book where it claims the bash shell ...

Dynamically building a command in bash

I am construcing a command in bash dynamically. This works fine: COMMAND="java myclass" ${COMMAND} Now I want to dynamically construct a command that redirectes the output: LOG=">> myfile.log ...

Perform OR on two hash outputs of sha1sum

I want perform sha1sum file1 and sha1sum file2 and perform bitwise OR operation with them using bash. Output should be printable i.e 53a23bc2e24d039 ... (160 bit) How can I do this? I know echo $(( ...

Set screen-title from shellscript

Is it possible to set the Screen Title using a shell script? I thought about something like sending the key commands ctrl+A shift-A Name enter I searched for about an hour on how to emulate ...

热门标签