Tippitytopkek
Tippitytopkek

Reputation: 315

How to get first word of every line and pipe it into dmenu script

I have a text file like this:

first state
second state
third state

Getting the first word from every line isn't difficult, but the problem comes when adding the extra \n required to separate every word (selection) in dmenu, per its syntax:

echo -e "first\nsecond\nthird" | dmenu

I haven't been able to figure out how to add the separating \n. I've tried this:

state=$(awk '{for(i=1;i<=NF;i+=2)print $(i)'\n'}' text.txt) 

But it doesn't work. I also tried this:

lol=$(grep -o "^\S*" states.txt | perl -ne 'print "$_"')

But same deal. Not sure what I'm doing wrong.

Upvotes: 1

Views: 534

Answers (4)

Daweo
Daweo

Reputation: 36520

In your code

state=$(awk '{for(i=1;i<=NF;i+=2)print $(i)'\n'}' text.txt)

you attempted to use ' inside your awk code, however code is what between ' and first following ', therefore code is {for(i=1;i<=NF;i+=2)print $(i) and this does not work. You should use " for strings inside awk code.

If you want to merely get nth column cut will be enough in most cases, let states.txt content be

first state
second state
third state

then you can do:

cut -d ' ' -f 1 states.txt | dmenu

Explanation: treat space as delimiter (-d ' ') and get 1st column (-f 1)

(tested in cut (GNU coreutils) 8.30)

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133528

This could be more easily done in while loop, could you please try following. This is simple, while is reading the file and during that its creating 2 variables 1st is named first and other is rest first contains first field which we are passing to dmenu later inside.

while read first rest
do
   dmenu "$first"
done < "Input_file"

Upvotes: 2

Jorge Bellon
Jorge Bellon

Reputation: 3106

Your problem is in the AWK script. You need to identify each input line as a record. This way, you can control how each record in the output is separated via the ORS variable (output record separator). By default this separator is the newline, which should be good enough for your purpose.

Now to print the first word of every input record (each line in the input stream in this case), you just need to print the first field:

awk '{print $1}' textfile | dmenu

If you need the output to include the explicit \n string (not the control character), then you can just overwrite the ORS variable to fit your needs:

awk 'BEGIN{ORS="\\n"}{print $1}' textfile | dmenu

Upvotes: 2

Raman Sailopal
Raman Sailopal

Reputation: 12877

Based on the text file example, the following should achieve what you require:

 awk '{ printf "%s\\n",$1 }' textfile | dmenu

Print the first space separated field of each line along with \n (\n needs to be escaped to stop it being interpreted by awk)

Upvotes: 0

Related Questions