3

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

9

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_.*"

  • 2
    absolutely right! – viavad Aug 18 '16 at 11:04
8

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
  • absolutely right! – viavad Aug 18 '16 at 11:06
  • very useful information – viavad Aug 18 '16 at 11:12
  • 2
    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 Aug 18 '16 at 11:49
6

Why grep, why not just:

ls -1 rm_*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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