Mohammad Shamsi
Mohammad Shamsi

Reputation: 13

how to add text to an output redirected to a file

I don't know if I'm wording it correctly, but I'm counting file types and outputting the results into a file, and instead of there just being numbers, I'm trying to identify what each number is. Sooo basically right now I have:

$ find . -type f -iname *.jpg* | wc -l > Test.md
$ find . -type f -iname *.png* | wc -l >> Test.md
$ find . -type f -iname *.tiff* | wc -l >> Test.md

and when I cat Test.md I get:

$ cat Test.md
13
10
8

and what I'm trying to do is:

JPG: 13
PNG: 10
TIFF: 8

Upvotes: 1

Views: 331

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185161

What I would do using a here-doc :

cat<<EOF>Test.md
JPG: $(find . -type f -iname '*.jpg*' | wc -l)
PNG: $(find . -type f -iname '*.png*' | wc -l)
TIFF: $(find . -type f -iname '*.tiff*' | wc -l)
EOF

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 141040

So just add the string without a newline before the count.

: > Test.md       # truncate the file
echo -n "JPG: " >> Test.md
find . -type f -iname '*.jpg*' | wc -l >> Test.md
echo -n "PNG: " >> Test.md
find . -type f -iname '*.png*' | wc -l >> Test.md
echo -n "TIFF: " >> Test.md
find . -type f -iname '*.tiff*' | wc -l >> Test.md

or like, grab the output of wc with command substitution, and pass to echo to do some formatting:

echo "JPG: $(find . -type f -iname '*.jpg*' | wc -l)" > Test.md
echo "PNG: $(find . -type f -iname '*.png*' | wc -l)" >> Test.md
echo "TIFF: $(find . -type f -iname '*.tiff*' | wc -l)" >> Test.md

Note: quote the *.jpg* argument for find inside single (or double) quotes to prevent filename expansion on the argument. find needs the argument with *, not literal filenames after the shell expansion.

Upvotes: 2

Related Questions