bash OSX 终端字符串长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21099205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:14:36  来源:igfitidea点击:

OSX terminal string length

bash

提问by Ahmed Nuaman

Is it possible in OSX's terminal to get the length of a string? Eg:

是否可以在 OSX 的终端中获取字符串的长度?例如:

$ echo "foo".length

Or

或者

$ echo (cat file.txt).length

回答by John Kugelman

echo "foo" | wc -c

This counts the number of characters on stdin. Note that this will return 4since echoadds a newline at the end. Use printfor echo -nto avoid the added newline.

这会计算 stdin 上的字符数。请注意,这将返回,4因为echo在末尾添加了一个换行符。使用printfecho -n避免添加换行符。

printf "foo" | wc -c

回答by dmarin

Try with this:

试试这个:

var=hello; echo ${#var}

回答by Adam

expr length can be used

可以使用 expr 长度

expr length "hello"
5

回答by Atish

The suggested solution adds 1 to the actual length. In my opinion, this is a better solution.

建议的解决方案将实际长度加 1。在我看来,这是一个更好的解决方案。

Added this to your .zshrc or .bash_profile

将此添加到您的 .zshrc 或 .bash_profile

lenFunc() {
  echo ${#1}
}

alias len=lenFunc

Then

然后

len foo
// output 3

回答by tonethar

From OS X Terminal, you can also use the Swift REPL to do so:

从 OS X 终端,您还可以使用 Swift REPL 来执行此操作:

user_name$ swift
Welcome to Apple Swift version 3.1 (swiftlang-802.0.53 clang-802.0.42).
Type :help for assistance.
  1> print("foo".characters.count)
3
  2>

In Swift 4 it would be print("foo".count)

在 Swift 4 中,它将是 print("foo".count)

回答by northtree

Faster way if the string is in your clipboard.

如果字符串在剪贴板中,则更快。

pbpaste | wc -c