我们在学习 laravel 过程中,从文档网页复制代码,会有一些比较麻烦的问题。以 《Laravel 10 中文文档》 | Laravel China 社区 (learnku.com) 为例
直接点复制按钮会带后,想测试的代码的话,还有处理 use 语句

选中复制时,网站会向剪贴板追加来源信息,还得手动处理。

这些手动处理起来,很浪费时间的,于是想到写个工具吧,专门用来处理这两个问题。
function watcher-laravel(){
local dir="app tests" # 先cd 到laravel 项目目录。这里是需要监控的文件和目录
inotifywait --event modify --format "%w%f" -mrq $dir | while read file; do
if [[ ! -f "$file" ]];then
continue
fi
local script=''
# 处理复制追加内容
if [[ -n "$(grep -Po '文链接' $file)" ]];then
script='/————————————————/,/文链接/d'
fi
# 处理 use 语句
if [[ -n "$(sed '/^namespace/,/^class\s/{/namespace/b; /class/b; d}' $file | grep -Po 'use\s+\w+.*;')" ]];then
local appends="$(grep -Po 'use\s+\w+.*;' $file | sort | uniq)"
script="$script ; /use\s+\w+.*;/d ; /namespace/a${appends//\\/\\\\}" #不对\转意的话,sed 会报错
fi
[ -n "$script" ] && sed -i -r "$script" $file # 不能写成简写成 -ir 够坑的
done
}