user3529379
user3529379

Reputation: 179

How to find the n-th word in a file (Linux Shell)

I'm trying to write a Shell Script that takes a file name and a number, and prints out the n-th word in the file. Is there any simple command that can do that?

Upvotes: 2

Views: 266

Answers (3)

donut
donut

Reputation: 790

You can try this

#!/bin/bash
awk -v var=$2 '{print $var}' < $1

Run example:

./script.sh filename.txt 30

Upvotes: 0

deinst
deinst

Reputation: 18782

If you want to deal with punctuation and multiple spaces try something like

#!/bin/bash
sed -e 's/[[:punct:]]*//g;s/[[:space:]]\+/\n/g' < $1 | sed $2q;d

Upvotes: 0

user3502260
user3502260

Reputation: 220

Try:

#!/bin/bash
tr '\n' ' ' < "$1" | cut -d' ' -f$2

Then run:

./script.sh filename.txt 30

Assumptions: words are separated by single spaces, words do not contain spaces.

Upvotes: 5

Related Questions