Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to list all files and select only certain from them. ls -1 return me the list

abc 
abcd
rm_0818-051752-753-06

after that I want to select only by this criteria to return the 3rd line so I do:

ls -1 | grep -E "^rm_.*"

but I get nothing.

I'm trying to recognize the first character of 3rd line in this way:

var=$(ls -1 | grep -E "rm_")
echo $var //returns rm_0818-051752-753-06
echo ${var:0:1} //returns some strange symbol 001B in square

Can you explain me this behavior and how could I grep by first character ^? Thanks

share|improve this question
up vote 3 down vote accepted

ls -1 | grep -E "^rm_.*" looks good and should work. Possible reason why it doesn't work is alias bound to ls command in your profile.
To ensure, try /bin/ls -1 | grep -E "^rm_.*"

share|improve this answer
1  
absolutely right! – viavad 2 hours ago

It sounds like you have grep aliased to grep --color=always or similar. You can check this by running type grep. I can reproduce a similar behavior:

$ var=$(ls -1 | grep --color=always "^rm")
$ echo ${var:0:1}
## Weird boxed character appears here

To see what's happening a bit better, we can pass $var through od:

$ echo "$var" | od -c
0000000 033   [   0   1   ;   3   1   m 033   [   K   r   m 033   [   m
0000020 033   [   K   _   0   8   1   8   -   0   5   1   7   5   2   -
0000040   7   5   3   -   0   6  \n
0000047

The 033 [ 0 1 ; 3 1 m 033 [ K are ANSI color escapes, and that's what's breaking here. You can avoid that by using an unaliased version of grep:

/bin/grep '^rm_'

or

\grep '^rm_'

Even better, don't parse ls since that often leads to other problems. A safer and simpler way of doing what you want is:

$ var="rm*"
$ echo $var
rm_0818-051752-753-06
$ echo ${var:0:1}
r
share|improve this answer
    
absolutely right! – viavad 2 hours ago
    
very useful information – viavad 2 hours ago
1  
In var="rm*" (or var=rm*), you're assigning rm* literally to $var, not rm_0818-051752-753-06. It's because you used the split+glob operator in the next line (echo $var), that you get rm_0818-051752-753-06 there. The echo ${var:0:1} will extract the r from rm*, not rm_0818-051752-753-06 – Stéphane Chazelas 1 hour ago

Why grep, why not just:

ls -1 rm_*
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.