簡體   English   中英

如何從bash中的文件內部加載列表?

[英]How do I load a list from inside a file in bash?

我是bash的新手,我只想從文件中加載列表,並提及所有以#;開頭的行; 應該被忽略(還有空的)。

如預期的那樣,每條有效行應成為列表中的一個字符串。

我需要對該列表的每個(有效)元素執行一些操作。

注意:我有一個for循環,例如for host in host1 host2 host3

您可以使用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
$ 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

如果您不擔心輸入中的空格,則只需使用

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

但通常在其他答案中使用數組和${array[@]}更為安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM