bash 壳牌:如何用“Cut”切割单个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24587021/
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 10:47:40  来源:igfitidea点击:

Shell: How to cut a single string with "Cut"?

bashshellshcutio-redirection

提问by Ryno

i'm trying to cut a string into the shell. I'd like to do something like:

我想把一根绳子剪进壳里。我想做类似的事情:

cut -d' ' -f1 "hello 12345 xyz" 

but the problem is that cut accept a file, so if i pass the string to it, it tries to open the unexistent file called "hello 12345 xyz" and then tries to cut its content

但问题是 cut 接受一个文件,所以如果我将字符串传递给它,它会尝试打开名为“hello 12345 xyz”的不存在的文件,然后尝试剪切其内容

I'd like to resolve this problem with the base programs, so don't tell me to use awk

我想用基本程序解决这个问题,所以不要告诉我使用 awk

thanks!

谢谢!

回答by anubhava

You can use Here Stringsin BASH:

您可以Here StringsBASH

cut -d' ' -f1 <<< "hello 12345 xyz"
hello

回答by chepner

There are several ways to do this in bashitself. If your string is already in a parameter (or you don't mind assigning it to one, you can use read:

有几种方法可以做到这一点bash。如果您的字符串已经在参数中(或者您不介意将其分配给一个,您可以使用read

str="hello 12345 xyz"
read first rest <<< "$str"

or parameter expansion:

或参数扩展:

echo "${str% *}"

or regular expression matching:

或正则表达式匹配:

[[ "hello 12345 xyz" =~ ([^ ]+)\  ]]
echo "${BASH_REMATCH[1]}"

回答by whereswalden

To get cutto act on a string instead of a file, you have to give it the string via STDIN. The most common way to do so is this:

cut对字符串而不是文件进行操作,您必须通过 STDIN 为其提供字符串。最常见的方法是这样的:

$ echo 'hello 12345 xyz' | cut -f 1
hello

回答by Jens

I don't exactly understand if you are needing this in a shell script, or when cutting the argument passed to a script, so I'll present solutions for both tasks. Note that not even cutis needed, since the shell can perform word-splitting based on white space by default with the setbuiltin.

我不完全明白您是在 shell 脚本中需要它,还是在剪切传递给脚本的参数时需要它,所以我将为这两个任务提供解决方案。请注意,甚至cut不需要,因为默认情况下,shell 可以使用set内置函数执行基于空格的分词。

If you have the string ina shell script,

如果您shell 脚本中有字符串,

 foo="hello 12345 xyz"
 set -- $foo
 echo     # hello

If the string is passedas the first argument to a shell script, as in script "hello 12345 xyz",

如果该字符串传递作为第一个参数的shell脚本,如script "hello 12345 xyz"

 set -- 
 echo