I am trying to write a command that examines a file which name has been given as a
parameter, and prints out the number of different lines containing exactly 7 characters.
I was doing it using grep and find, but I am going wrong.
What should I use, or what pattern?
-
Can you give an example file (with contents) and our exact desired output?chaos– chaos2017-06-28 09:02:33 +00:00Commented Jun 28, 2017 at 9:02
-
give some example contents of file. if you want to count the lines which is having exactly 7 characters, then you can use this. grep -c "^.......$" filenameKamaraj– Kamaraj2017-06-28 09:02:49 +00:00Commented Jun 28, 2017 at 9:02
2 Answers
This could be your command. It's a script that takes a filename on the command line and outputs all lines in it that has exactly seven characters:
#!/bin/sh
grep -c '^.......$' "$1"
You have to make the above script executable (with something like chmod +x script.sh), and then run it with ./script.sh file where file is the name of the file that you'd like to examine.
The command
grep -c '^.......$'
will output the number of lines in the given file that contains exactly seven characters (including spaces).
This may be shortened to
grep -cEx '.{7}'
The -E in necessary because the expression is now an extended regular expression. The -x flag will force the expression to match a full line.
If you don't want to count spaces and you're only interested in "word characters" (alphanumerics), you may use
grep -cExw '.{7}'
The -w flag to grep will force the match to be a "word" (a string of alphanumeric characters delimited by non-alphanumeric characters).
If you want to count how many unique lines there are that fulfill this criteria (this is how I interpret "different lines"), then pipe the result of grep without the -c flag through uniq and wc -l. This will count the number of unique lines with exactly seven word characters.
grep -Exw '.{7}' | uniq | wc -l
In the script, this becomes
grep -Exw '.{7}' "$1" | uniq | wc -l
perl -l -0777pe '$_ =()= /^.{7}$/gm' "$1"
awk 'length == 7' "$1" | wc -l
sed -Ee '/.{8}/d; /.{7}/!d' "$1" | grep -c .