简体   繁体   中英

Bash: Take argument 1 of each line in a file and put it into an array

I have a file that contains many lines. Each line consists of first, a 1 word string, and second, a number (argument 1 and argument 2 are separated by a space). I need to create a script that goes through each line, and assigns argument 1 to an array, and argument 2 to another array. I then need to print both arrays in the same order they were in (in the file) using a loop. Then I must bubble sort the strings (arg1) in alphabetical order, but the numbers (arg2) must follow the string in the same order they were in when they were in the file. I then need to print both arguments (now alphabetical, but with original numbers along side) in their new sorted order.

Here is what I assume it should look like, but I can't get working:

for line in ${filename[*]}; do
    for (( i=0; i<=${#filename[*]}; i++ )); do
        array=( $(array + arg1) )
    done
done

The "array + arg1" is just what I can't figure out. I just can't seem to find out how to get the 1st argument of each line and put it into an array. You'd think it would be simple.

There are many ways to do what you need, here is one as an example:

My file list, with 1 word string and a number for each line:

cat mylist.txt
word_b 20
word_h 80
word_c 30
word_e 50
word_d 40
word_f 60
word_g 70
word_a 10

So, you can do something like this:

#!/bin/bash

# Declare arrays
words_array=()
numbers_array=()

# Read line by line from SORTED file list
filename="mylist.txt"
IFS=$'\n'
for line in `cat $filename | sort`; do
  # Assign the word in the first position and the number in the second to variables
  word=$(echo $line|awk '{print $1}')
  number=$(echo $line|awk '{print $2}')
  # Append values to each array
  words_array+=("$word")
  numbers_array+=("$number")
done

# Then use loop and share iterator between arrays
for (( i=0; i<=${#words_array[@]}; i++ )); do
  echo  "${words_array[$i]} ${numbers_array[$i]}"
done

Output:

./myscript.sh
word_a 10
word_b 20
word_c 30
word_d 40
word_e 50
word_f 60
word_g 70
word_h 80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM