Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent grep from printing a trailing newline?

I am using grep to produce output that will be parsed by another program.

However, that program expects output only to be numeric or zero-bytes.

Now grep outputs a newline character after its output. I've checked the -Z option but it doesn't seem to work as I'm using grep for counting (-c).

I am executing in sh, not bash. So nesting it into echo -n "$(grep -c pattern)" doesn't work either.

How can I get rid off the trailing newline?

like image 555
Cobra_Fast Avatar asked Aug 30 '11 20:08

Cobra_Fast


People also ask

How can I grep without newline?

The `` or $() will remove the newline from the end, but to do this programatically, use tr . This will remove the carriage return and/or the newline from the string.

How can I grep without printing?

To suppress the default grep output and print only the names of files containing the matched pattern, use the -l ( or --files-with-matches ) option.

How do you grep an empty line?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '.


2 Answers

Use tr -d to delete characters in a string:

$ grep -c ' ' /etc/passwd | tr -d '\n' 69$ grep -c ' ' /etc/passwd | tr -d '\n' | xxd  0000000: 3639                                     69 $  
like image 52
Johnsyweb Avatar answered Sep 23 '22 14:09

Johnsyweb


You can pipe it through tr and translate the \n to a \0 character:

tr '\n' '\0' 
like image 42
Amardeep AC9MF Avatar answered Sep 23 '22 14:09

Amardeep AC9MF