user2076851
user2076851

Reputation: 41

Making multiple commands appear on the same output line

Hi I keep having trouble with this

echo 'Welcome to my first Script'
mkdir myScript
cd myScript
touch doc1 sales.doc.test2.txt outline.doc

echo 'You now have ' ;find . -type f|wc -l;echo 'files in your "myScript" folder'

address="205"
echo -n "Please enter your favourite number:"
read myvar
echo "The number you entered is $myvar"

I'm trying to make the output say "You now have (3) files in your myScript folder" as one line, but it keeps outputting them on 3 seperate lines. I've tried 3 or 4 different codes here (by clicking the similar questions above) but they give me funny errors and this is just my first script, so I understand all the commands I'm using (minus the calculation for files, I had to google that one).

Upvotes: 4

Views: 5205

Answers (4)

chepner
chepner

Reputation: 531035

Use the printf command:

printf 'You now have %d files in your "myScript" folder' $( find . -type f | wc -l )

(A slight variation on the other answers using command substitution embedded in the string.)

Upvotes: 0

carlpett
carlpett

Reputation: 12583

echo "You now have $(find . -type f|wc -l ) files in your \"myScript\" folder"

Additionally, I'd recommend altering the find to include -maxdepth 1, otherwise you'll recurse...

Upvotes: 7

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

They are on separate lines because echo and wc output newlines.

One way around it is this:

echo 'You now have' $(find . -type f | wc -l) 'files in your "myScript" folder'

Here we get rid of extra echo newline because we use one echo to rule them all. We get rid of wc newline because with this kind of substitution, the output of wc is broken into words and those words are passed to echo as separate arguments; word separators are lost (echo uses space to separate its arguments on output).

Upvotes: 3

Use the no-new-line switch -n and echo the result of your find:

echo -n 'You now have ' ; echo -n "`find . -type f|wc -l`"; echo -n ' files in your "myScript" folder'

Upvotes: 2

Related Questions