Linux 如何在bash中将结果转换为整数
当我这样做的时候Linux 如何在bash中将结果转换为整数,linux,bash,awk,sed,Linux,Bash,Awk,Sed,当我这样做的时候 $ ls | wc -l 703 它给了我结果703,我想打印702(703-1) 如何在bash中执行此操作?您可以使用算术展开: result=$(( $(ls | wc - l) - 1)) 或者忽略其中一个文件 result=$(ls | tail -n+2 | wc -l) 请注意,如果文件名包含换行符,则不起作用;在这种情况下,使用ls-q每行获取一个文件名。这也适用于第一种解决方案,如果您感兴趣的是文件的数量,而不是它们名称中的行数。(无礼的回答)在计数之前
$ ls | wc -l
703
它给了我结果703,我想打印702(703-1)
如何在bash中执行此操作?您可以使用算术展开:
result=$(( $(ls | wc - l) - 1))
或者忽略其中一个文件
result=$(ls | tail -n+2 | wc -l)
请注意,如果文件名包含换行符,则不起作用;在这种情况下,使用ls-q
每行获取一个文件名。这也适用于第一种解决方案,如果您感兴趣的是文件的数量,而不是它们名称中的行数。(无礼的回答)在计数之前从输出中删除一行:D
ls | sed“1d”| wc-l
如何在bash中将结果转换为整数
@choroba已经回答了这个问题,它应该解决OP的问题。然而,我想对他的回答补充更多
OP希望将结果转换为整数,但是Bash
没有任何类似Integer
的数据类型
与许多其他编程语言不同,Bash不按“类型”分隔变量。本质上,Bash变量是字符串,但根据上下文,Bash允许对变量进行算术运算和比较。决定因素是变量的值是否只包含数字
有关Bash中的算术运算,请参见
有关了解Bash的非类型化本质的最佳示例,请参见。我已经发布了以下示例:
#!/bin/bash
# int-or-string.sh
a=2334 # Integer.
let "a += 1"
echo "a = $a " # a = 2335
echo # Integer, still.
b=${a/23/BB} # Substitute "BB" for "23".
# This transforms $b into a string.
echo "b = $b" # b = BB35
declare -i b # Declaring it an integer doesn't help.
echo "b = $b" # b = BB35
let "b += 1" # BB35 + 1
echo "b = $b" # b = 1
echo # Bash sets the "integer value" of a string to 0.
c=BB34
echo "c = $c" # c = BB34
d=${c/BB/23} # Substitute "23" for "BB".
# This makes $d an integer.
echo "d = $d" # d = 2334
let "d += 1" # 2334 + 1
echo "d = $d" # d = 2335
echo
# What about null variables?
e='' # ... Or e="" ... Or e=
echo "e = $e" # e =
let "e += 1" # Arithmetic operations allowed on a null variable?
echo "e = $e" # e = 1
echo # Null variable transformed into an integer.
# What about undeclared variables?
echo "f = $f" # f =
let "f += 1" # Arithmetic operations allowed?
echo "f = $f" # f = 1
echo # Undeclared variable transformed into an integer.
#
# However ...
let "f /= $undecl_var" # Divide by zero?
# let: f /= : syntax error: operand expected (error token is " ")
# Syntax error! Variable $undecl_var is not set to zero here!
#
# But still ...
let "f /= 0"
# let: f /= 0: division by 0 (error token is "0")
# Expected behavior.
# Bash (usually) sets the "integer value" of null to zero
#+ when performing an arithmetic operation.
# But, don't try this at home, folks!
# It's undocumented and probably non-portable behavior.
# Conclusion: Variables in Bash are untyped,
#+ with all attendant consequences.
exit $?
echo$($(ls | wc-l)-1))
??甚至更好的是,(set--*;shift;echo$#)
不完全正确。在bash
中,一个被视为整数值的字符串可以以一个基本说明符作为前缀:echo$(010))
输出8,但echo$((10#010))
输出10
。关键是。纯字符串也将被视为参数引用echo$((foo))
如果foo
unset,则输出0<代码>foo=3;echo$((foo))输出3。