【问题标题】:using sed in bash script在 bash 脚本中使用 sed
【发布时间】:2012-10-06 20:50:58
【问题描述】:

使用通过 grep 命令获取的行号数组,我尝试增加行号并使用 sed 命令检索新行号上的内容,但我假设我的语法有问题(特别是 sed 部分,因为其他一切都有效。)

脚本如下:

#!/bin/bash


#getting array of initial line numbers    

temp=(`egrep -o -n '\<a class\=\"feed\-video\-title title yt\-uix\-contextlink  yt\-uix\-sessionlink  secondary"' index.html |cut -f1 -d:`)

new=( )

#looping through array, increasing the line number, and attempting to add the
#sed result to a new array

for x in ${temp[@]}; do

((x=x+5))

z=sed '"${x}"q;d' index.html

new=( ${new[@]} $z ) 

done

#comparing the two arrays

echo ${temp[@]}
echo ${new[@]}

【问题讨论】:

    标签: regex linux bash sed grep


    【解决方案1】:

    这可能对你有用:

    #!/bin/bash
    
    
    #getting array of initial line numbers    
    
    temp=(`egrep -o -n '\<a class\=\"feed\-video\-title title yt\-uix\-contextlink  yt\-uix\-sessionlink  secondary"' index.html |cut -f1 -d:`)
    
    new=( )
    
    #looping through array, increasing the line number, and attempting to add the
    #sed result to a new array
    
    for x in ${temp[@]}; do
    
    ((x=x+5))
    
    z=$(sed ${x}'q;d' index.html) # surrounded sed command by $(...)
    
    new=( "${new[@]}" "$z" ) # quoted variables
    
    done
    
    #comparing the two arrays
    
    echo "${temp[@]}" # quoted variables
    echo "${new[@]}"  # quoted variables
    

    你的 sed 命令没问题;它只需要被$(...) 包围,并删除和重新排列不必要的引号。

    顺便说一句

    获取模式后五行的行(GNU sed):

    sed '/pattern/,+5!d;//,+4d' file
    

    【讨论】:

      【解决方案2】:

      你的 sed 行应该是:

      z=$(sed - n "${x} { p; q }"  index.html) 
      

      请注意,我们使用“-n”标志告诉 sed 只打印我们告诉它的行。当我们到达存储在“x”变量中的行号时,它将打印它(“p”)然后退出(“q”)。为了允许扩展 x 变量,我们发送给 sed 的 commabd 必须放在双引号之间,而不是单引号之间。

      以后使用 z 变量时,你应该把它放在双引号之间。

      希望这有帮助 =)

      【讨论】: