从命令行串联文件内容

时间:2019-09-14 17:30:48

标签: linux shell

我正在寻找创建一个shell脚本,该脚本读取命令行参数,然后将那些文件的内容连接起来并将其打印到stdout。这仅适用于文本文件。

到目前为止,我已经创建了一个错误检查以确保至少有一个参数,否则将打印错误。我已经弄清楚了如何获取当前目录中的文件并将它们连接到stdout。

#!/bin/bash

if [ $# -eq 0 ]; then
    echo -e "Usage: concat FILE ...\nDescription: Concatenates 
FILE(s) to standard output separating them with divider -----."
    exit 1
fi

for f in *.txt; do (cat "${f}"; echo "-----"); done
exit 0

我需要调整此代码以在串联任何文件之前测试文件是否存在,并且我需要它读取命令行参数并且仅串联指定的文件。截至目前,此代码将当前目录中包含“ .txt”的所有内容串联起来

此脚本需要能够处理任意数量的参数,并且内容中的文本用“ -----”分隔,且未插入多余的空行。

我是Shell的新手,对此有点麻烦。

谢谢!

2 个答案:

答案 0 :(得分:1)

您提到要检查文件是否存在。您对* .txt的全局扩展应该可以有效地做到这一点,但是如果您有额外的偏执狂,可以添加一个文件测试操作符:

if [ -f $f ];
then
   # file exists do do your stuff as above
else
   echo "whoa, that file $f that existed 4ms ago is no longer  there!"
fi

答案 1 :(得分:0)

您可以执行以下操作:

#!/bin/bash

for file in "$@"                     ## This will loop through all the variables.
do
  ## This will check if file with txt extenstion exists or not 
  if [ -f $file ] && [ "$(echo $file|awk -F'.' '{print $NF}')" == "txt" ]
  then
    cat $file >> con.txt             ## This will keep on concatenating.
  fi
done