sed命令从文件中选择一定数量的行

时间:2014-09-11 07:15:27

标签: shell sed aix

我正在尝试拆分巨大的文件,每个文件都包含30k左右的行。 我发现它可以使用sed -n'from_line,to_line p'命令完成,但如果我有行号,它工作正常但在我的情况下,我使用两个变量,我得到错误。

这是我正在使用的脚本。

k=1
for i in `ls final*`
do
    count=`wc -l $i|awk '{print $1}'`

    marker1=1
    marker2=30000
    no_of_files=$(( count/30000 ))

    #echo $no_of_files
    no_of_files=$(( no_of_files+1 ))

    while [[ no_of_files -ne 0 ]];do

        if [[ $marker2 -gt $count ]];then
            sed -n '$marker1,$count p' $i > purge$k.txt
        else
            sed -n '$marker1,$marker2 p' $i > purge$k.txt
            marker1=$(( marker2+1 ))
            marker2=$(( marker2+30000 ))
        fi

        no_of_files=$(( no_of_files-1 ))
        k=$(( k+1 ))
    done 
done

我在运行脚本时遇到错误。

sed: $marker1,$marker2 p is not a recognized function.
sed: $marker1,$marker2 p is not a recognized function.
sed: $marker1,$marker2 p is not a recognized function.
sed: $marker1,$marker2 p is not a recognized function.
sed: $marker1,$marker2 p is not a recognized function.
sed: $marker1,$marker2 p is not a recognized function.
sed: $marker1,$count p is not a recognized function.

3 个答案:

答案 0 :(得分:1)

它不起作用可能是因为你在''

中使用变量

尝试更改sed命令,如下所示

sed -n "$marker1,$count p"

或更好的是

sed -n '/'$marker1'/,/'$count'/p'

答案 1 :(得分:0)

一些小变化。
sed中使用双引号。不要使用旧的背部抽搐,请使用括号 将k=$(( k+1 ))更改为((k++))

k=1
for i in $(ls final*)
    do
    count=$(wc -l <$i)
    marker1=1
    marker2=30000
    no_of_files=$(( count/30000 ))
    #echo $no_of_files
    (( no_of_files++ ))
    while [[ no_of_files -ne 0 ]];do
        if [[ $marker2 -gt $count ]];then
            sed -n "$marker1,$count p" $i > purge$k.txt
        else
            sed -n "$marker1,$marker2 p" $i > purge$k.txt
            marker1=$(( marker2+1 ))
            marker2=$(( marker2+30000 ))
        fi
        (( no_of_files-- ))
    (( k++ ))
    done 
done

wc -l $i|awk '{print $1}'可以像这样使用:

awk 'END {print NR}' $i

wc -l < $i

答案 2 :(得分:0)

正如其他人所说,你的shell变量在单引号内,所以它们没有被展开。但是你使用的是错误的工具。你正在做什么使用N次传递创建N个文件。 split -l 30000 "$i"会将文件拆分为30,000行,称为xaa,xab,...您可以告诉分割调用xaa文件的内容。

相关问题