实用的shell命令

Posted by Distiny on February 11, 2023

操作find到的所有文件

find . -type f | while read file;do 
# 对$file 进行操作
done

统计当前文件夹和各个子文件夹文件个数

find . -maxdepth 1 -type d| while read dir; do
echo "in dict $dir"
find $dir -type f | wc -l
done

修改json文件,在前面添加其他项

#!/bin/bash

# 定义要搜索的目录
dir="./"

# 使用 find 命令搜索所有 json 文件
find $dir -type f -name "*.json" | while read filename; do
  # 读取文件内容,并将其作为 "_source" 项
  source=$(cat "$filename")
  
  # 将文件名作为 "_id" 值
  id=$(basename "$filename" .json)
  
  # 将 "_type": "_doc"、"_id" 和 "_source" 的值组合成 JSON 字符串
  output="{\"_type\":\"_doc\",\"_id\":\"$id\",\"_source\":$source}"
  
  # 输出结果
  echo "$output" > $filename
done