用于创建编号的文件列表的Shell脚本

时间:2017-06-18 04:51:00

标签: bash shell sh

我是一个shell脚本初学者。我已经试图解决这个问题已经有一段时间了,我仍然不知道,我应该如何编写这个shell脚本以便它可以工作。我有多个文本文件,其中包含数据。我需要的是编写一个脚本,创建一个包含文件数据的编号列表。

示例:我有四个文件,“file_A”,“file_B”,“file_C”和“file_D”。每个都有一些文字。基本上我需要使用类似“script.sh output_file file_A file_B file_C file_D”的内容将其传输到新文件中,以便输出文件如下所示:

  1. file_A“file_A中的文字”
  2. file_B“来自file_B的文字”
  3. file_C“file_C中的文字”
  4. file_D“来自file_D的文字”
  5. 好的,现在我知道我可以将echo“$ file_#”和cat“$ file_#”重定向到>>“$ output_file”,但是如何让它重复工作以获取更多的输入文件使用参数?我想我需要使用for循环,对吗?如何添加编号?我应该为这个行计数函数设置一个变量吗?

    感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您可以尝试以下解决方案,它对我有用

    #!/bin/bash
    #index to refer file number
    index=0
    #var to store output file name
    outputFile="$1"
    #clear output file before writing
    echo "" > $outputFile
    #iterate through all args
    for file in "$@"
    do
            if [ $index -eq 0 ] #skip first arg as it contain output file  
            then
                    index=$((index+1))
                    continue
            fi
            echo "$index. $file " `cat $file` >> $outputFile  #append file index, name & text to output file
            index=$((index+1))
    done

<强>输出:

  1. file1 Random txt 1

  2. file2 Random txt 2

答案 1 :(得分:0)

其中一种方法:

#!/bin/bash

# first argument is output file
output_file=$1 
shift

# shift through rest of the arguments
while [ $# -ne 0 ] 
do
    echo "$((counter+=1)). $1 '$(cat $1)'" >> $output_file
    shift
done