[关闭]
@ysongzybl 2015-04-30T18:33:16.000000Z 字数 864 阅读 2597

Bash read lines from file into string array

bash


Best way to do

  1. array=()
  2. # Read the file in parameter and fill the array named "array"
  3. getArray() {
  4. i=0
  5. while read line # Read a line
  6. do
  7. array[i]=$line # Put it into the array
  8. i=$(($i + 1))
  9. done < $1
  10. }
  11. getArray "file.txt"

How to use your array :

  1. # Print the file (print each element of the array)
  2. getArray "file.txt"
  3. for e in "${array[@]}"
  4. do
  5. echo "$e"
  6. done

The simplest way to read each line of a file into a bash array is this:

  1. #!/bin/bash
  2. IFS=$'\n' read -d '' -r -a lines < /etc/passwd
  3. # Now just index in to the array lines to retrieve each line, e.g.
  4. printf "line 1: %s\n" "${lines[0]}"
  5. printf "line 5: %s\n" "${lines[4]}"
  6. # all lines
  7. echo "${lines[@]}"

split string

  1. #!/usr/bin/env bash
  2. IN="bla@some.com;john@home.com"
  3. arr=$(echo $IN | tr ";" "\n")
  4. for x in $arr
  5. do
  6. echo "> [$x]"
  7. done

Reference

1 http://stackoverflow.com/questions/11393817/bash-read-lines-in-file-into-an-array
2 http://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注