bash - 在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':没有这样的文件或目录“我怎样才能实现交换?此外,将不胜感激对代码的任何改进。
解决方案
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
推荐阅读
- logstash - Logstash - 解析 JSON 数组
- c# - 在 Blazor Wasm 中读取本地/静态文件
- python - Python Plotly Dash - 如何在不使用回调的情况下访问更新的组件值?
- youtube-api - YouTube API 配额激增
- python - 用火花执行python脚本
- dynamics-crm - 从 CRM 上传到 CosmosDB 时出现分区错误
- r - 根据 R 中的特定变量选择不同的条目
- wordpress - NGINX SSL 反向代理上的 WordPress Docker 无法按预期工作
- node.js - 找不到命令:ts-node-dev
- python - 如何将 Lat Lon 坐标的 Pandas DataFrame 转换为矩阵?(Python)