Sunday, April 10, 2022

[SOLVED] how can I highlight just one item from the ls output

Issue

real beginner in Unix commands so not sure if the following is actually possible but here goes. Is it possible to highlight just one item in a ls output?

I.e.: in a directory I use the following

ls -l --color=auto

this lists 4 items in green

file1.xls
file2.xls
file3.xls
file4.xls

But I want to highlight a specific item, in this case file2. Is this possible?


Solution

The ls program will not do this for you. But you could filter the results from ls through a custom script which modifies the text to highlight just one item. It would be simpler if no color was originally given; then you could match on the given filename (for example as the pattern in an awk script, or in a sed script) and modify just that one item, adding colors.

That is, certainly it is possible. Writing a sample script is a different question.

How you approach the problem depends on what you want from the output. If that is (literally) the output from ls with a single filename in color, then a script would be the normal approach. You could use grep as suggested in the other answer, which raises a few issues:

  • commenting on ls -l --color=auto makes it sound as if you are using GNU ls, hence likely using Linux. An appropriate tag for the question would be linux rather than unix. If you ask for unix, the answers should differ.
  • supposing that you are using Linux. Then likely you have GNU grep, which can do colors. That would let you do something like this:

    ls -l | grep --color=always file2 |less -R

  • however, there is a known bug in GNU grep's use of color (see xterm FAQ "grep --color" does not show the right output).
  • using grep like this shows only the matching lines. For ls that might be a good choice. For matches in a manual page -- definitely not.

Alternatively, less (which is found more often on Unix systems than GNU grep) also can highlight matches (not in color) and would show the file you are looking for in context. You could do this:

ls -l | less -p file2

(Both grep and less use patterns aka regular expressions, but I left the example simple — read the documentation to learn more).



Answered By - Thomas Dickey
Answer Checked By - Terry (WPSolving Volunteer)