如何通过bash中的索引获取特定单词

时间:2018-11-10 12:11:40

标签: bash shell text

我有一个脚本,该脚本带有以下参数:

script.sh 1 3

然后我想浏览一个文本文件,并从每一行中打印出第一个和第三个单词。我根本不知道该怎么做。如果有人能帮助我,我将非常感激...

这是我目前拥有的:

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

1 个答案:

答案 0 :(得分:3)

使用observableOfInserts.startWith(observableWithCurrentDbItems).subscribe(processSingleItem)

awk

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

file

输出为:

1 2 3 4 5
6 7 8 9 0

在bash脚本中:

1 3
6 8

使用此脚本,您可以传递任意数量的索引:

对于1和2:

#!/bin/bash

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

对于1、2和5:

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