Raph117
Raph117

Reputation: 3821

How to get specific words by index in a line bash

I have a script that takes parameters such as:

script.sh 1 3

I want to then go through a text file and print out the first and third words from each line. I have simply no idea how to do this. If anyone could help I'd really appreciate it...

This is what I currently have:

counter=0
wordcounter=0

param=$(echo "$3" | tr , " ") 

words(){
    for word in $1; do
        for col in $param; do
            if [ $wordcounter -eq $col ]; then
                echo $word
            fi
        done 
    done
    wordcounter=$((wordcounter + 1))
}

eachline() {
    newline=$(echo "$1" | tr , " ")
    for word in $newline; do
        if [ $counter -gt 3 ]; then
            echo "$word"
        fi
        counter=$((counter + 1))
    done
    if [ $counter -gt 0 ]; then 
        words "$newline"
    fi
    counter=$((counter + 1))
}

while read line; do
    eachline $line
done < company/employee.txt

Upvotes: 0

Views: 1454

Answers (1)

Denis Zavedeev
Denis Zavedeev

Reputation: 8297

Use awk:

$ awk '{print $1 " " $3}' file

for file:

1 2 3 4 5
6 7 8 9 0

Output is:

1 3
6 8

In bash script:

#!/bin/bash

awk_command="{print";
for i in "$@"; do
    awk_command="${awk_command} \$${i} \" \"";
done    
awk_command="${awk_command}}";
awk "$awk_command" file

With this script you can pass any number of indexes:

For 1 and 2:

$ ./script.sh 1 2
1 2 
6 7 

For 1, 2 and 5:

$ ./script.sh 1 2 5
1 2 5 
6 7 0 

Upvotes: 3

Related Questions