Reading lines in a file and avoiding lines with # with Bash

后端 未结 10 1988
清歌不尽
清歌不尽 2020-12-03 06:47

I tried this:

file=\"myfile\"
while read -r line
do
    [[ $line = \\#* ]] && continue
    \"address=\\$line\\127.0.0.1\"
done < \"$file\"
         


        
相关标签:
10条回答
  • 2020-12-03 07:40

    This could also be accomplished with 1 sed command:

    file="myfile"
    
    sed -i".backup" 's/^#.*$//' $file
    

    This will modify the file in-place (creating a backup copy first), removing all lines starting with a #.

    0 讨论(0)
  • 2020-12-03 07:44

    It's safer to use [[ "$line" = "\#*" ]]

    Btw, address="\\${line}\\127.0.0.1"

    UPD:

    If I've understand you right you need to change every uncommented domains to address=\domain\127.0.0.1. It could be done fast and easy with sed, there is no need in bash-program.

    $> cat ./text
    domain1.com
    domain2.com
    domain3.com
    #domain4.com
    domain5.com
    
    $> sed -r -e 's/(^[^#]*$)/address=\/\1\/127.0.0.1/g' ./text2
    address=/domain1.com/127.0.0.1
    address=/domain2.com/127.0.0.1
    address=/domain3.com/127.0.0.1
    #domain4.com
    address=/domain5.com/127.0.0.1
    

    If you need to remove commented lines, sed can do it too with /matched_line/d

    $> sed -r -e 's/(^[^#]*$)/address=\/\1\/127.0.0.1/g; /^#.*$/d' ./text2 
    address=/domain1.com/127.0.0.1
    address=/domain2.com/127.0.0.1
    address=/domain3.com/127.0.0.1
    address=/domain5.com/127.0.0.1
    

    UPD2: if you want to do all that stuff inside the bash script, here is your code modification:

    file="./text2"
    while read -r line; do
        [[ "$line" =~ ^#.*$ ]] && continue
        echo "address=/${line}/127.0.0.1"
    done < "$file"
    

    And it's output:

    address=/domain1.com/127.0.0.1
    address=/domain2.com/127.0.0.1
    address=/domain3.com/127.0.0.1
    address=/domain5.com/127.0.0.1
    
    0 讨论(0)
  • 2020-12-03 07:47

    To skip lines starting with #:

    grep -v '^#' myfile | while read -r file ; do
        ...
    done
    

    Modify the grep command as needed to, for example, skip lines starting with whitespace and a # character.

    0 讨论(0)
  • 2020-12-03 07:48

    Only one working for me was:

    while IFS=$'\n' read line
    do  
        if [[ "$line" =~ \#.* ]];then
            logDebug "comment line:$line"
        else
            logDebug "normal line:$line"
        fi
    done < myFile
    
    0 讨论(0)
提交回复
热议问题