如何在bash中使用除法执行此计数行操作

时间:2015-05-05 22:51:57

标签: bash shell

我的目标是将文件拆分成块。假设我有一个包含100行的文件。 我想使用bash脚本将其分成4个块。我这样做的方法是计算文档中有多少行。然后,我指定要分割的文档数。我计算得到chucks的行号,然后使用split命令和-l选项。

我试过了:

    echo "Please specify the number of chunks you want to split"
    read chunks
    echo "Preparing the input files......................"
    echo "Please Enter your input file directory"
    read inputDir
    echo "Spliting the input file into chunks"
    split -l=$(($((wc -l $inputDir))/$(($chunks-1)))) $inputDir

它给了我这个错误:(假设我在这里输入5并想要获得4个文件,每个25行)

    syntax error: operand expected (error token is "/3")

1 个答案:

答案 0 :(得分:1)

wc输出它计算的文件的名称。为防止这种情况,请使用重定向:

$(( $(wc -l < $inputDir) / (chunks - 1) ))

$inputFile是一个更好的变量名,除非你真的想要处理一个目录。但是,您无法使用wc计算目录中的行数。

另请注意,您不需要嵌套算术扩展$((...))

此外,您的split可能支持-n选项:

  

-n, - number = CHUNKS

     

生成CHUNKS输出文件。