Reputation: 179
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
Reputation: 790
You can try this
#!/bin/bash
awk -v var=$2 '{print $var}' < $1
Run example:
./script.sh filename.txt 30
Upvotes: 0
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
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