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 can use
sed
along withgrep
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.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.
Can you try whether this command helps you
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=" "