I would like to use the grep command to print a line number for the string I'm searching for. However, when I used the command grep -n it prints the line number with a colon : next to it. Is there any way I can use the same grep -n command to print a line number with it being followed by the : colon?

$ grep -n 'Captain' sometextfile.txt
3: Captain America

I would like it to instead print,

3 Captain America

(without the ':' )

Any suggestions??

  • You cannot do it using grep options only. Try: grep 'Captain' sometextfile.txt | cat -n – muru Dec 10 '14 at 17:57
  • @muru But the line numbers will still change to 1,2,3... – Rohith Madhavan Dec 10 '14 at 18:07
  • @RohithMadhavan Then you can reverse the order: cat -n sometextfile.txt | grep ... – muru Dec 10 '14 at 18:08
  • @muru Yes. That will work. – Rohith Madhavan Dec 10 '14 at 18:10

You can use sed along with grep to achieve this.

grep -n 'Captain' sometextfile.txt | sed 's/:/ /'

This sed command finds the pattern : and replaces it with (a space).

General Syntax - sed 's/find/replace/'

This method will replace only the first occurence of : in each line with . Therefore, even if a line in the text file contains :, it will remain unaffected.

| improve this answer | |

If you just want to delete the colon (and not replace it with a space), you can pipe the output of your grep statement through tr. Your command would be something like:

grep -n 'Captain' sometextfile.txt | tr -d ':'

If you want to replace the colon with a space, you can use:

grep -n 'Captain' sometextfile.txt | tr ':' ' '

Though, as muru points out, this will remove any colons in the line.

| improve this answer | |
  • 2
    And what if the matched lines contain :? – muru Dec 10 '14 at 18:09

Can you try whether this command helps you

awk '/Captain America/ {printf "%s %s\n", NR, $0}'
| improve this answer | |

Here's my two cents on the question, use awk sub function :

grep -n 'Captain' file.txt | awk '{sub(":"," "); print }'

grep -n 'Captain' file | awk '{sub(":Captain"," Captain"); print }'

And here's cut ( which removes all traces of : like in dazzle's example ):

grep -n 'Captain' file | cut -d":" -f1- --output-delimiter=" "

| improve this answer | |

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.