2012-04-18 21 views
1

私はbashを初めて使いました。ファイルからリストをロードしたいだけで、#または;で始まるすべての行を無視する必要があります(空の場合もあります)。bashのファイル内からリストをロードするにはどうしたらいいですか?

予想通り、各有効な行はリスト内の文字列になります。

このリストの各(有効な)要素で何らかのアクションを実行する必要があります。

注:私はfor host in host1 host2 host3のようなforループを持っています。

+4

本当にリストを保存する必要がありますか?データ構造は、bashの強力なポイントではありません。 grepまたはawkコマンドの出力を実際にリストを処理するプログラムにパイプするだけで十分です。 – chepner

+0

正しい、改善された質問:P – sorin

答えて

5

あなたは配列にファイルを読み取るためにbashの組み込みコマンドmapfileを使用することができます。

# read file(hosts.txt) to array(hosts) 
mapfile -t hosts < <(grep '^[^#;]' hosts.txt) 

# loop through array(hosts) 
for host in "${hosts[@]}" 
do 
    echo "$host" 
done 
1
$ cat file.txt 
this is line 1 

this is line 2 

this is line 3 

#this is a comment 



#!/bin/bash 

while read line 
do 
    if ! [[ "$line" =~ ^# ]] 
    then 
     if [ -n "$line" ] 
     then 
      a=("${a[@]}" "$line") 
     fi 
    fi 
done < file.txt 

for i in "${a[@]}" 
do 
    echo $i 
done 

出力:

this is line 1 
this is line 2 
this is line 3 
+0

bashのバージョン(pre-4.0?)に 'mapfile'がないと便利です。 – chepner

0

あなたが入力中にスペースを心配していない場合は、単純に使用することができます

for host in $(grep '^[^#;]' hosts.txt); do 
    # Do something with $host 
done 

の配列の使用と他の答えの${array[@]}は一般に安全です。

関連する問題