LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Server (https://www.linuxquestions.org/questions/linux-server-73/)
-   -   Find length of fist line of all txt files (https://www.linuxquestions.org/questions/linux-server-73/find-length-of-fist-line-of-all-txt-files-4175589432/)

kenw232 09-14-2016 03:08 PM

Find length of fist line of all txt files
 
I want to loop through all the .TXT files in a directory and get the length of the first line of each one.

find /path -name "*.txt" -exec head -n1 {} \;
will print the first line of each file, now how do I print the LENGTH of the first line of each file? like "300" for 300 characters long.

Sefyir 09-14-2016 03:20 PM

Use wc

Code:

echo hello | wc -c
6

Code:

      -c, --bytes
              print the byte counts


kenw232 09-14-2016 03:24 PM

ya buts its counting all the output together

Code:

find . -name "*.php" -exec head -n1 {} \; | wc -c
1364901


Sefyir 09-14-2016 03:30 PM

You can use a while loop to pipe each line found with find

Code:

while read i;
do head -n1 "$i" | wc -c
done < <(find . -name \*.php)

You can also use parallel

Code:

parallel 'head -n1 {} | wc -c' ::: \*.php

kenw232 09-14-2016 03:35 PM

This is good. Now I just need a condition if the length from wc is equal to say 400 to do something. How do I tell this to do a sed command if the length of the first line is 400 characters?

PHP Code:

while read i;
do 
head -n1 "$iwc -c
done 
< <(find . -name \*.php


Sefyir 09-14-2016 03:42 PM

This can easily be done with a if conditional expression.

Feel free to use man bash and search for CONDITIONAL EXPRESSIONS

Here's a search to get you started

eg this guide

kenw232 09-14-2016 03:50 PM

yes I can do a conditional expression. but how to I capture the number of wc into a variable to check?

Sefyir 09-14-2016 03:59 PM

You can use command substitution for that.

Code:

variable=$(echo hello | wc -c)

echo $variable
6


Habitual 09-14-2016 04:04 PM

Couting characters, words, lenght of the words and total lenght in a sentence

and
https://www.google.com/#q=count+word...in+bash+script

Read.
Study.
Try.
Question.

MadeInGermany 09-18-2016 10:40 AM

Code:

find /path -name "*.txt" |
while IFS= read -r file
do
  read line <"$file"
  if [[ ${#line} -eq 400 ]]
  then
    echo "${file}: line1 is 400"
  fi
done



All times are GMT -5. The time now is 07:47 PM.