简体   繁体   English

如何从bash中的文件内部加载列表?

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

I'm new to bash and I just want to load a list from a file mentioning that all the lines starting with # or ; 我是bash的新手,我只想从文件中加载列表,并提及所有以#;开头的行; should be ignored (and also empty ones). 应该被忽略(还有空的)。

As expected each valid line should became a string in the list. 如预期的那样,每条有效行应成为列表中的一个字符串。

I need to perform some action with each (valid) element of this list. 我需要对该列表的每个(有效)元素执行一些操作。

Note: I have a for loop like for host in host1 host2 host3 . 注意:我有一个for循环,例如for host in host1 host2 host3

You can use bash builtin command mapfile to read file to an array: 您可以使用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

outputs: 输出:

this is line 1
this is line 2
this is line 3

If you aren't worried about spaces in the input, you can simply use 如果您不担心输入中的空格,则只需使用

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

but the use of arrays and ${array[@]} in the other answers is safer in general. 但通常在其他答案中使用数组和${array[@]}更为安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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