-1

I want to search for the match count of a specific word/pattern in all files below a certain directory. However, I want the number to appear directly after the filename.

I did the following but it writes the count to a new line instead of the last line

grep -rc "WORD" /home/user/data >> file

Actual output

foo
12

Desired output:

foo12

2 Answers 2

1

With >> file, the file is opened on stdout in append mode. So any output goes at the end of the file.

grep writes 12\n. Your file contained foo\n beforehand. So you get foo\n12\n. To get foo12\n, you'd need not to output at the end, but at the last byte before then end, to overwrite that \n with 12\n.

Some shells have operators for that.

With zsh:

zmodload zsh/system
if sysseek -u 1 -w end -1; then
  grep -c WORD /home/user/data
else
  syserror -p "Can't seek to just before the end: "
fi 1<> file

With ksh93:

grep -c WORD /home/user/data 1<> file >#((EOF - 1))

<> is the redirection operator that opens files in read+write mode. Here, we don't care about the read part, but we use <> as contrary to >, it doesn't truncate files.

In any case, that is not an append mode. You'll see a difference if some other process also writes to the file or truncates it at the same time (unlikely to be a problem in your case).

Another approach could be to truncate the file to remove the trailing \n, and then open the file in append mode.

With GNU truncate:

truncate -s -1 file && grep -c WORD /home/user/data >> file
0

You can use sed to append at the end of the last line:

sed -i '$ s/$/'$(grep -rc "WORD" /home/user/data)'/' file

See also: append text with echo without new line

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.