简体   繁体   中英

Using grep, ls to get a file in bash

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.

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

Use shell wildcards, as in

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):

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

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.

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

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

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

#!/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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM