Pass the value of a variable to a command as if it were stored in a file - bash

I am interested in counting the number of lines in the output of ps command which I can do with
echo "$(ps | wc -l)"
However, I now have the output of ps command stored in a variable by doing X="$(ps)". How do I pass X to wc -l command without using a pipe? I tried $(wc -l < "$X") but it didn't work. I read the man page for wc and it takes a file as an argument. So I guess another way to frame the question would be - How do I treat value of a variable as a file to pass as an argument to a command in bash script?
I am fairly new to bash scripting and keywords I tried to search with didn't give clear answer to my questions.

I suggest:
echo "$X" | wc -l
or
wc -l <<< "$X"

Related

bash: how to implement the output of 'wc -l' as an argument to another script

I have a script: 'analysis.pl' where the number of lines in a separate file are required as an input argument:
perl ./analysis.pl max=[input number of lines in separate file]
It would be very useful if I could give the output of 'wc -l separate_file' as input to the perl script.
max=`wc -l NRL.txt`
echo $max
perl ./analysis.pl max=$max
The problem is that wc -l gives the number of lines and the file name which returns an error as the argument can only take one input....
perl ./analysis.pl max=150000 separate_file ####error
So how can I get wc -l to only return the number of lines and not the file name?
when passing file as standard input wc doesn't echo filename
wc -l < NRL.txt
There are many ways to solve this specifically, but one way is to pipe the output of wc to awk and pull the number out of the output of wc:
max=`wc -l NRL.txt | awk '{print $1}'`

Error in script

I am new to bash and scripting and I am trying to create a simple script but for some reason it won't let me run this:
fileCount= ls -1 | wc -l
#echo $fileCount
for (( i=0; i<$fileCount; ++i )) ; do
echo item: $i
done
Whenever I try to run this it just gives me an error message saying it expected an operand.
I am really confused on the error here and any help would be greatly appreciated!
To get your code running with minimal change, replace:
fileCount= ls -1 | wc -l
With:
fileCount=$(ls -1 | wc -l)
$(...) is called command substitution. It is what you use when you want capture the output of a command in a variable.
It is very important that there be no spaces on either side of the equal sign.
Improvements
To speed up the result, use the -U option to turn off sorting.
To prevent any attempt to display special characters, use -q.
Thus:
fileCount=$(ls -1Uq | wc -l)
Lastly, when ls is writing to something other than a terminal, such as, in this command, a pipeline, it prints one file name per line. This makes -1 optional.
you missed to assign the output of wc -l to your variable. Try this:
fileCount=$(ls | wc -l)
(option "-1" is not needed, because ls writes one file per line if its stdout is not a terminal)

shell script that takes a string input by the user and outputs the number of characters in it?

Please can you show me a shell script that takes a string input by the user and outputs the number of characters in it? I have tried numerous times but i can't get it right.
Use the wc function like that:
echo -n abc | wc -c
or
echo -n abc | wc -m
The -n supresses the final newline which would count as an extra character.
check manual for wc.
This should do the trick:
#!/usr/bin/env bash
echo -n "$1" | wc -c
wc is a tool to count characters, lines or bytes. -c is the option for characters.
The -n option for echo avoids the newline which would be an extra character.
Make sure to make the script executable by:
chmod +x wordcount.sh
So you will get:
user#host$ ./wordcount.sh "My String"
9

Output number of lines in a text file to screen in Unix [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
bash echo number of lines of file given in a bash variable
Was wondering how you output the number of lines in a text file to screen and then store it in a variable.
I have a file called stats.txt and when I run wc -l stats.txt it outputs 8 stats.txt
I tried doing x = wc -l stats.txt thinking it would store the number only and the rest is just for visual but it does not work :(
Thanks for the help
There are two POSIX standard syntax for doing this:
x=`cat stats.txt | wc -l`
or
x=$(cat stats.txt | wc -l)
They both run the program and replace the invocation in the script with the standard output of the command, in this case assigning it to the $x variable. However, be aware that both trim ending newlines (this is actually what you want here, but can be dangerous sometimes, when you expect a newline).
Also, the second case can be easily nested (example: $(cat $(ls | head -n 1) | wc -l)). You can also do it with the first case, but it is more complex:
`cat \`ls | head -n 1\` | wc -l`
There are also quotation issues. You can include these expressions inside double-quotes, but with the back-ticks, you must continue quoting inside the command, while using the parenthesis allows you to "start a new quoting" group:
"`echo \"My string\"`"
"$(echo "My string")"
Hope this helps =)
you may try:
x=`cat stats.txt | wc -l`
or (from the another.anon.coward's comment):
x=`wc -l < stats.txt`

bash echo number of lines of file given in a bash variable without the file name

I have the following three constructs in a bash script:
NUMOFLINES=$(wc -l $JAVA_TAGS_FILE)
echo $NUMOFLINES" lines"
echo $(wc -l $JAVA_TAGS_FILE)" lines"
echo "$(wc -l $JAVA_TAGS_FILE) lines"
And they both produce identical output when the script is run:
121711 /home/slash/.java_base.tag lines
121711 /home/slash/.java_base.tag lines
121711 /home/slash/.java_base.tag lines
I.e. the name of the file is also echoed (which I don't want to). Why do these scriplets fail and how should I output a clean:
121711 lines
?
An Example Using Your Own Data
You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:
NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")
Explanation: Use Pipes or Redirection to Avoid Filenames in Output
The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:
# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd
# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41
# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41
# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41
As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.
wc can't get the filename if you don't give it one.
wc -l < "$JAVA_TAGS_FILE"
You can also use awk:
awk 'END {print NR,"lines"}' filename
Or
awk 'END {print NR}' filename
(apply on Mac, and probably other Unixes)
Actually there is a problem with the wc approach: it does not count the last line if it does not terminate with the end of line symbol.
Use this instead
nbLines=$(cat -n file.txt | tail -n 1 | cut -f1 | xargs)
or even better (thanks gniourf_gniourf):
nblines=$(grep -c '' file.txt)
Note: The awk approach by chilicuil also works.
It's a very simple:
NUMOFLINES=$(cat $JAVA_TAGS_FILE | wc -l )
or
NUMOFLINES=$(wc -l $JAVA_TAGS_FILE | awk '{print $1}')
I normally use the 'back tick' feature of bash
export NUM_LINES=`wc -l filename`
Note the 'tick' is the 'back tick' e.g. ` not the normal single quote

Resources