Find words that are 6 characters in length
Asked Answered
B

5

5

I have a file.txt

fhadja
ksjfskdasd
adasda
sada
s
adasaaa

I need to extract only the words that are 6 character length from there.

EXAMPLE of what i need to obtain as a result:

fhadja
adasda

Thank you.

Baculiform answered 30/9, 2015 at 19:49 Comment(0)
S
8

You can use:

grep -E '^.{6}$' file
fhadja
adasda

Or using awk:

awk 'length($0)==6' file
fhadja
adasda

Or using sed:

sed -rn '/^.{6}$/p' file
fhadja
adasda
Swann answered 30/9, 2015 at 19:51 Comment(2)
but if I need also all the words that starts with letter "f" and with the length 6? Thank you!Baculiform
Then use: grep -E '^f.{5}$' fileSwann
W
4

Try this with GNU grep:

grep -E '^.{6}$' file

Output:

fhadja
adasda
Woodwind answered 30/9, 2015 at 19:51 Comment(0)
H
1

Or perl:

perl -ne 'print if 6 == tr/\n//c' file
Hatband answered 30/9, 2015 at 19:55 Comment(0)
H
1

Just for fun: Another solution in bash

while read -r line
do
    if [ ${#line} -eq 6 ]
    then
      echo $line
    fi
done < file.txt

you get,

fhadja
adasda
Hescock answered 30/9, 2015 at 19:58 Comment(0)
H
0

If your file can contain spaces, make sure you're matching non-blank characters:

grep -oE '\<[[:graph:]]{6}\>' << END
 fhadja
   ksjfskdasd
   adasda
   sada s 123456
   s
 2 4 6
END
fhadja
adasda
123456
Halutz answered 30/9, 2015 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.