Cat 文件做一些操作从文件输出追加到第一个文件

Cat file do some operation append from file output to first file

我正在努力实现以下目标:

  #!/bin/bash
  if [ -f file2 ]; then

  cat file2 > file1
  sed -i 's#some operation' file1
  cat file3 >> file1

  exit 0

  elif [ ! -f file2 ]; then

  cat file1 > file2
  sed -i 's#some operation' file1
  cat file3 >> file1

  exit 0

  else

  echo "something"
  exit 1

  fi

任何想法如何使它更简单? 不用那么多猫和文件?

谢谢!

sed -i 's# some operation' file1
cat file2 >> file1

对于你原来的问题:

cat file1 > file1.bak
sed -i 's# some operation' file1.bak
cat file2 >> file1.bak
echo -n > file1
cat file1.bak > file1
rm -f file1.bak

更简单的答案是(正如我在评论中所说):

sed -i 's# some operation' file1
cat file2 >> file1

对于编辑过的问题 - 多一点解释。

您的情况:

#!/bin/bash
if [ -f file2 ]; then
...
elif [ ! -f file2 ]; then
...
else
...
fi

else永远不会发生。 如果 file1 存在并且是常规文件。 if-then 将 运行,如果您否定上述内容,将 运行 elif-then。例如。你可以将其简化为

if [ -f file2 ]; then
...
else
...
fi

现在开始行动:

那个:

cat file2 > file1
sed -i 's#some operation' file1
cat file3 >> file1

等同于:

sed 's#some operation' <file2 >file1
cat file3 >> file1

和:

cat file1 > file2
sed -i 's#some operation' file1
cat file3 >> file1

没问题 - 您创建了 file1file2 的备份(副本)。这也可以写成 cp file1 file2.

比较这两个部分,你在做同样的事情:

cat file3 >> file1

所以,DRY(不要重复自己)- 并在 if 之后执行此操作,因为这对两个部分都是通用的。

所以,我们得到:

if [ -f file2 ]; then
    sed 's#some operation' <file2 >file1
else
    cp file1 file2  #make the copy
    sed -i 's#some operation' file1
fi
cat file3 >> file1

此外,

sed 's#some operation' <file2 >file1
#and
sed -i 's#some operation' file1

非常相似 - 例如sed 操作的结果总是进入 file1。此外,在 else 中,您将 file1 复制到 file2,因此

cat file1 > file2
sed -i 's#some operation' file1

也可以写成

cp file1 file2
sed 's#some operation' <file2 >file1

对于这两种情况,我们都得到了相同的 sed 命令,所以 - 再次 DRY。

if [ -f file2 ]; then
    : #do nothing here...
else
    cp file1 file2  #make the copy
fi
sed 's#some operation' <file2 >file1
cat file3 >> file1

但是do nothing部分是不必要的,所以我们得到:

if [ ! -f file2 ]; then
    cp file1 file2  #make the copy
fi
sed 's#some operation' <file2 >file1
cat file3 >> file1

这可以使用 [[ condition ]] && ... 缩短,但目前不需要。 :)

另外,非常有助于更准确地命名您的文件。 file1 等等 - 什么都不告诉你内容。