Using grep to print line numbers

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??

4

4 Answers

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.

0

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.

1

Can you try whether this command helps you

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

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=" "

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like