You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用sed和awk将文件名(不含扩展名)写入文件指定位置

Replace \exname{target} with Filename (Without .Rnw) in .Rnw Files

Got it, let's sort out this reverse operation you need—swapping out the target in \exname{target} with the corresponding filename (minus the .Rnw extension) for each of your .Rnw files. Below are two solid approaches using sed and awk, along with breakdowns so you know what's going on:

1. Using sed (GNU or macOS)

Sed is perfect for quick text substitutions. We'll loop through all .Rnw files, extract the base filename, and replace the target string:

for file in *.Rnw; do
  # Strip the .Rnw extension to get the base filename
  base_name="${file%.Rnw}"
  # Replace \exname{target} with \exname{base_name}, and backup the original file
  sed -i.bak "s/\\exname{target}/\\exname{$base_name}/" "$file"
done

Quick notes:

  • -i.bak creates a backup of your original file (e.g., test1.Rnw.bak) in case you need to revert. If you don't want backups, use -i (GNU sed) or -i '' (macOS sed—don't skip the empty string here, it's required).
  • We double the backslashes (\\) because sed treats backslashes as escape characters, so we need to escape the backslash in \exname to match it correctly.

2. Using awk (Cross-Platform)

If you prefer awk, or need more flexibility down the line, this approach works reliably across all systems:

for file in *.Rnw; do
  base_name="${file%.Rnw}"
  # Pass the base filename to awk as a variable, then do the substitution
  awk -v fname="$base_name" '{gsub(/\\exname{target}/, "\\exname{"fname"}"); print}' "$file" > temp_file && mv temp_file "$file"
done

Quick notes:

  • -v fname="$base_name" passes the base filename into awk as a variable named fname, so we can use it in the substitution.
  • gsub() handles global substitution (replaces all instances of \exname{target} in the file—though you probably only have one per file).
  • We redirect output to a temporary file first, then replace the original file—awk doesn't have a built-in "in-place edit" option like sed, so this is the safe way to modify files directly.

Example Result

For your test1.Rnw file, after running either command, the line:

\exname{target}

Will become:

\exname{test1}

内容的提问来源于stack exchange,提问作者exl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:48:46