使用 grep, ls 在 bash 中获取文件

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

Using grep, ls to get a file in bash

bashunixgrep

提问by guenis

I'm trying to write a bash script which would locate a single file in the current directory. The file will be used later but I don't need help there. I tried using ls and grep but it doesn't work, I'm a newbie using bash.

我正在尝试编写一个 bash 脚本来定位当前目录中的单个文件。该文件将在稍后使用,但我不需要那里的帮助。我尝试使用 ls 和 grep 但它不起作用,我是使用 bash 的新手。

#!/bin/sh
#Here I need smt like
#trFile = ls | grep myString (but I get file not found error)
echo $trFile

采纳答案by lornix

#!/bin/sh
#
trfile=$( ls | grep myString )
echo $trfile

The $( xxx ) causes the commands within to be executed and the output returned.

$( xxx ) 导致执行其中的命令并返回输出。

回答by dannysauer

Use shell wildcards, as in

使用 shell 通配符,如

ls *${pattern}*

And, to store the result in a variable, put it inside a $()structure (you can also use deprecated backticks if you like using deprecated functionality that doesn't nest well)

并且,要将结果存储在变量中,请将其放入$()结构中(如果您喜欢使用不推荐使用的嵌套不好的功能,也可以使用不推荐使用的反引号)

var=$( ls *${pattern}* )

Or, put your ls | grep in there (but that's bad practice, IMHO):

或者,把你的 ls | grep 在那里(但这是不好的做法,恕我直言):

var=$( ls | grep -- "$pattern" )

回答by MeloMCR

I believe you are looking for something like this:

我相信你正在寻找这样的东西:

    #!/bin/sh
    trFile=`ls | grep "$myString"`

In order to run a command and redirect/store its output, you need put the command between backticks. The variable that will store the output, equal sign and the backtick need to be together, as in my example. Hope this helps.

为了运行命令并重定向/存储其输出,您需要将命令放在反引号之间。存储输出的变量、等号和反引号需要放在一起,就像我的例子一样。希望这可以帮助。

回答by t0mm13b

Try this, if I guess what you're trying to do is, get the capture of the filename from grepping via the output of the lsinto a shell variable, try this:

试试这个,如果我猜你想要做的是,grep通过ls到 shell 变量的输出从ping获取文件名的捕获,试试这个:

#!/bin/sh

trFile=`ls | grep "name_of_file"`
echo $trFile

Notice the usage of the back-tick operator surrounding the command, what-ever is the output, in this case, will get captured.

请注意命令周围的反引号运算符的使用,在这种情况下,无论输出是什么,都将被捕获。

回答by Mantosh

using output of ls will bite when you least expect. Better use Globbing. http://tldp.org/LDP/abs/html/globbingref.html

使用 ls 的输出会在您最不期望的时候咬人。更好地使用通配符。 http://tldp.org/LDP/abs/html/globbingref.html