传递包含特殊字符的变量以在bash中进行sed [英] passing variable containing special chars to sed in bash

查看:48
本文介绍了传递包含特殊字符的变量以在bash中进行sed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文件中删除子域:

I need to remove subdomains from file:

.domain.com
.sub.domain.com -- this must be removed
.domain.com.uk
.sub2.domain.com.uk -- this must be removed

所以我用过sed:

sed '/\.domain.com$/d' file
sed '/\.domain.com.uk$/d' file

这部分很简单,但是当我尝试在循环中进行操作时,会出现问题:

and this part was simple, but when i try to do it in the loop problems appears:

while read line
do
sed '/\$line$/d' filename > filename   
done < filename

我想它是."和$ problem,已经尝试了多种方式进行转义,但是我现在没有主意了.

I suppose it is "." and $ problem , have tried escaping it in many ways but i am out of ideas now.

推荐答案

受NeronLeVelu的想法启发的解决方案:

A solution inspired by NeronLeVelu's idea:

#!/bin/bash

#set -x

domains=($(rev domains | sort))

for i in `seq 0 ${#domains[@]}` ;do
    domain=${domains[$i]}
    [ -z "$domain" ] && continue
    for j in `seq $i ${#domains[@]}` ;do
        [[ ${domains[$j]} =~ $domain.+  ]] && domains[$j]=
    done
done


for i in `seq 0 ${#domains[@]}` ;do
    [ -n "${domains[$i]}" ] && echo ${domains[$i]} | rev >> result.txt
done

对于 cat域:

.domain.com
.sub.domain.com
.domain.co.uk
.sub2.domain.co.uk
sub.domain.co.uk
abc.yahoo.com
post.yahoo.com
yahoo.com

您得到 cat result.txt :

.domain.co.uk
.domain.com
yahoo.com

这篇关于传递包含特殊字符的变量以在bash中进行sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆