How to find specific word by lenght from specific file?

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
kingz

How to find specific word by lenght from specific file?

Post by kingz »

Hello there,

Suppose i have this huge dictionary .txt in my system. Now i need to write a shell script that takes a numeric input from the user( $1 ), the number the user input is supposed to specify the lenght of the word the user is looking for in the dictionary txt.
In other words the output should look like this:

$./myegrep 3

aim
aaa
etc
Ian
Lan
Net

$./myegrep 5

Arthur
Crave
Grave
Since


Got it? Also i am trying to do this without using any kind of loops/if statements whatsoever. It should be a simple egrep one line with a regular expression, but i am having trouble figuring out how to implement the user input into the regular expression. Any help? Thanks in advance!
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Habitual

Re: How to find specific word by lenght from specific file?

Post by Habitual »

would be helpful if you showed us your script, as "Arthur" is 6 characters long. :shock:
User avatar
xenopeek
Level 25
Level 25
Posts: 29615
Joined: Wed Jul 06, 2011 3:58 am

Re: How to find specific word by lenght from specific file?

Post by xenopeek »

I've put your lines into a file called testfile. Here's example of using egrep to get lines 3, 5 or 6 characters long:

Code: Select all

$ egrep ^.{3}$ testfile
aim
aaa
etc
Ian
Lan
Net
$ egrep ^.{5}$ testfile
Crave
Grave
Since
$ egrep ^.{6}$ testfile
Arthur
In a script you could use:

Code: Select all

#!/usr/bin/env bash
egrep ^.{$1}$ testfile
Pass this script the length you are looking for and it will return the lines from testfile that match that length.

Edit: to get better at bash go read these two, highly recommended:
- http://mywiki.wooledge.org/BashGuide
- http://mywiki.wooledge.org/BashFAQ/
Image
Locked

Return to “Scripts & Bash”