首页 > 解决方案 > 在bash脚本的目录中交换两个文件

问题描述

我正在编写一个脚本,它读取目录中的两个文件,显示内容,交换文件并再次显示内容。

我研究了如何交换两个文件并获得了交换方法。但是,当我运行脚本时,该方法给了我一个错误。

#!/bin/sh
file1="$1"
file2="$2"

function readFile() {
for file in `ls`
do
  cat $file
done

}
function swap()
{
echo "Swapping"
TMP=$(mktemp -d)

 mv "$1" $TMP/tempfile
 mv "$2" "$file1"
 mv $TMP/tempfile "$file2"
 [ -e $TMP/tempfile ] && echo "Error!" || rm -r $TMP
 }
 cd ~
 cd test

 readFile $file1 $file2
 swap $file1 $file2
 readFile $file1 $file2

我收到一个错误“ mv:无法统计'':没有这样的文件或目录 mv:无法统计'':没有这样的文件或目录 mv:无法统计'/tmp/tmp.jduY2Yk6xi/tempfile':没有这样的文件或目录“我怎样才能实现交换?此外,将不胜感激对代码的任何改进。

标签: bashshell

解决方案


Based on your question I am not sure this meets all your criteria. But if you just need a content swap of 2 files, you use this very simple script.

It will accept the 2 files you want to swap. Read the contents of each. Save the first file as tmp. Then overwrite file1 with the contents of file2. Then, overwrite file2 with the contents of the tmp file(file1). Lastly it will read the contents again

#!/bin/sh
file1="$1"
file2="$2"

cat  $file1 $file2
mv $file1 tmp
mv $file2 $file1
mv tmp $file2
cat  $file1 $file2

To run this

script.sh file1.txt file2.txt

results

World 
hello
hello
World

推荐阅读