🔍パソコンの中から、特定の言葉を探したい!
たとえば「ウェブサイトのデータ(HTML)」の中から、特定のキーワードが含まれるファイルを探したい とき。
こんな感じのRスクリプトで一発です✨
指定ディレクトリとそのサブディレクトリを再帰的に探索していくよ!
💡キーワードが入っているHTMLファイルだけを表示 してくれるので、サイト更新や文章の見直しにも便利です♪
📦使用するパッケージ
パッケージ | 用途 |
---|---|
fs | フォルダやファイルを調べる |
stringr | 文字列を探す&変える |
rvest | 今回は出番なしですが、HTML解析に使えます💡 |
🗃️キーワードを検索する
📁ディレクトリ構造
SearchHTML/
├── SearchHTML.Rproj
└── search_keyword.R
⬅️Rスクリプト
# SearchHTML/search_keyword.R
library(fs) # 📦フォルダ&ファイルの操作
library(stringr) # 📦文字列検索の魔法
# 📁探したい場所を指定!(↓書き換えればOK)
target_dir <- "your/directory/path"
# 📝探したい言葉をセット!
keyword <- "探したいキーワード"
# 📂HTMLファイルを全部取得(サブフォルダもOK!)
html_files <- dir_ls(path = target_dir, recurse = TRUE, glob = "*.html")
# 🗃️マッチしたファイルを入れる箱
matching_files <- c()
# 🔍ファイルの中をチェック!
for (file in html_files) {
file_content <- readLines(file, warn = FALSE, encoding = "UTF-8")
if (any(str_detect(file_content, fixed(keyword)))) {
matching_files <- c(matching_files, file)
}
}
# 結果を表示♪
if (length(matching_files) > 0) {
cat("🔍 見つかったファイルはこちら!:\n")
print(matching_files)
} else {
cat("⚠️ 残念…該当ファイルはありませんでした。\n")
}
🔁キーワードをまとめて置き換えたい!
検索できるなら、置き換えもしたい! ということで、
今度は「前の言葉を、新しい言葉に」入れ替えるスクリプトを書いてみました。
📝 例えば「株式会社●●」を「株式会社△△」に一気に変更、みたいな作業にもぴったり。
メールアドレスや電話番号が変わったときにも💯
💡書き換えたファイルは そのまま上書き保存 されるので、使うときは バックアップ推奨 です!(ここ重要)
🗃️キーワードを置換する
📁ディレクトリ構造
ReplaceKeyword/
├── ReplaceKeyword.Rproj
└── replace_keyword.R
⬅️Rスクリプト
# ReplaceKeyword/replace_keyword.R
library(fs) # 📦フォルダ&ファイルの操作
library(stringr) # 📦文字列検索の魔法
# 📁探したい場所を指定!(↓書き換えればOK)
target_dir <- "your/directory/path"
# 📝「前の言葉」と「変えたい言葉」をセット!
old_keyword <- "置換前の文字列"
new_keyword <- "置換後の文字列"
# 📂HTMLファイルを全部取得(サブフォルダもOK!)
html_files <- dir_ls(path = target_dir, recurse = TRUE, glob = "*.html")
# 🔁置換
for (file in html_files) {
file_content <- readLines(file, warn = FALSE, encoding = "UTF-8")
if (any(str_detect(file_content, fixed(old_keyword)))) {
cat("🔁 置換中:", file, "\n") # ←どのファイルを直してるか表示!
# 💫文字をまるっと置き換え!
new_content <- str_replace_all(file_content, fixed(old_keyword), new_keyword)
# 💾元のファイルに上書き保存
writeLines(new_content, file, useBytes = TRUE)
}
}
cat("✅ 完了:すべてのHTMLファイルに対して置換処理を実行しました〜!\n")
🖥️HTML以外も!ファイル一覧をCSVで出力したい!
「どのフォルダに、どんなファイルがあったっけ…?」って時、ありませんか?
私はよくあります!(笑)
そんなときは、このスクリプトで HTML・画像・Excel・Word・PDF ファイルを全部探して、一覧(CSVファイル)で出力 してくれます✨
CSVなので、Excelで開いて確認できますよ〜📊✨
出力されるもの
- パス(場所)
- サイズ
- 更新日時
🗃️指定ディレクトリ以下のファイル(HTML、画像、Excel、Word、PDF)の一覧を種類ごとにcsvで出力する
📁ディレクトリ構造
ListFiles/
├── ListFiles.Rproj
└── list_files.R
⬅️Rスクリプト
# ListFiles/list_files.R
library(fs) # 📦フォルダ&ファイルの操作
# 📁探したい場所を指定!(↓書き換えればOK)
target_dir <- "your/directory/path"
# 📍出力ファイルの名前につける目印(今回はフォルダ名)
output_prefix <- target_dir
# 🎯探したいファイルの拡張子グループ
file_types <- list(
html = c("*.html"),
images = c("*.png", "*.gif", "*.jpg", "*.jpeg"),
excel = c("*.xls", "*.xlsx"),
word = c("*.doc", "*.docx"),
pdf = c("*.pdf")
)
# 🔍ファイル一覧をそれぞれ出力(CSV形式)
for (type in names(file_types)) {
patterns <- file_types[[type]]
files <- unlist(lapply(patterns, function(pat) {
dir_ls(path = target_dir, recurse = TRUE, glob = pat)
}))
if (length(files) > 0) {
# 📂ファイル情報を取得(パス、サイズ、更新日時)
info <- file_info(files)
output_data <- data.frame(
path = info$path,
size_bytes = info$size,
modified_time = info$modification_time
)
# ✒️出力ファイル名(CSV形式)
output_file <- file.path(target_dir, paste0("file_list_", type, ".csv"))
write.csv(output_data, file = output_file, row.names = FALSE, fileEncoding = "UTF-8")
cat("✅ CSV出力完了:", output_file, "\n")
} else {
cat("⚠️ 対象ファイルが見つからなかったよ〜(", type, ")\n")
}
}
テキストファイルで出力したい場合は、出力ファイル名の拡張子と、出力関数を変えてね♪
CSV版 | TXT版 |
---|---|
.csv | .txt |
write.csv(…) | write.table(…, sep = "\t", quote = FALSE) |
⬅️R、すごい…!!
1000個以上のファイル があっても軽々こなしてくれるんです!(ありがたや🙏)
ぜひ一度、試してみてください〜!