pwc101 |
08-07-2009 07:12 AM |
Quote:
Originally Posted by brainlesseinstein
(Post 3634671)
I want to grep a string variable that is provided by the user as input but it has a space between the two strings
Actually I want user to input a specific date in the format "Aug 4" and then use this variable to list files from a directory for that date.
read -p "Enter Date=" date; //date is in the format Aug 4
cd xyz;
ls -ltr | grep `echo $date` //this does not work
|
Put double quotes around the "$date":
Code:
read -p "Enter Date=" date;
cd xyz;
ls -ltr | grep "$date"
I've removed the backticks (which I would have replaced with the $() syntax since I find it easier to read) and the unnecessary call to echo.
Beware, however, of trying to identify files in a directory based on their modification date using this method. On my machine, the output of ls -ltr looks as follows:
Code:
drwxr-x--- 9 pwc101 gg 4096 Dec 18 2006 evolution
lrwxrwxrwx 1 pwc101 gg 29 Jan 25 2007 scratch -> /data/geophys/scratch/pwc101/
lrwxrwxrwx 1 pwc101 gg 18 Apr 17 2007 central -> /noc/data/central/
lrwxrwxrwx 1 pwc101 gg 23 Jul 6 2007 pubread -> /noc/itg/pubread/pwc101
drwxr-x--- 2 pwc101 gg 72 Nov 21 2007 docs
lrwxrwxrwx 1 pwc101 gg 28 Mar 5 2008 data -> /data/geophys/general/pwc101
drwxr-x--- 10 pwc101 gg 4096 Aug 28 2008 src
drwx------ 3 pwc101 gg 49 Oct 9 2008 Desktop
drwxr-x--- 3 pwc101 gg 19 Nov 23 2008 candy
lrwxrwxrwx 1 pwc101 gg 24 Jan 28 2009 ng -> /noc/gg/general_geophys/
drwxr-x--- 7 pwc101 gg 4096 Feb 10 10:25 tmp
lrwxrwxrwx 1 pwc101 gg 30 Mar 25 18:00 ns -> /noc/gg/scratch_geophys/pwc101
drwx------ 3 pwc101 gg 30 Mar 26 12:52 mail
drwxr-x--- 2 pwc101 gg 4096 Apr 13 09:19 exec
drwxr-x--- 8 pwc101 gg 82 May 29 18:11 bin
Thus, if I had entered as the answer to your question, I'd get no results from the grep since the actual string in the output of ls is You might want to sanitise the output of ls through sed or tr, perhaps, before passing it to grep.
Just a thought :)
|