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

Unix下提取文件末行首词并删除另一文件对应后续行的方法

Solution to Extract Target Word and Remove Next Line in Unix

Got it, let's walk through how to solve this problem step by step—we'll use standard Unix command-line tools that you probably already have installed.

Step 1: Extract the target word from FILE1.txt

First, we need to grab the first word of the last line in FILE1.txt. The easiest way to do this is combining tail (to fetch the last line) and awk (to print the first field):

target_word=$(tail -n 1 FILE1.txt | awk '{print $1}')

This will store camelot (from your sample FILE1.txt) in the target_word variable.

Step 2: Remove the line after the target word in FILE2.txt

Now we have two reliable approaches to modify FILE2.txt:

Approach 1: Using awk (portable across most Unix systems)

Awk is ideal for line-by-line text processing. This script will skip the line immediately after any line containing our target word:

awk -v target="$target_word" '
    skip_next_line { skip_next_line = 0; next }
    $0 ~ target { skip_next_line = 1 }
    1  # Print the current line unless we skipped it
' FILE2.txt > temp_file.txt && mv temp_file.txt FILE2.txt
  • -v target="$target_word" passes our variable into awk
  • When we hit a line with the target, we set skip_next_line to 1
  • The next line triggers skip_next_line, so we reset it and skip printing that line
  • We write to a temp file first because you can't modify a file in-place directly with awk; then we replace the original file.

Approach 2: Using sed (simpler, note platform differences)

Sed is perfect for quick text edits. This command will match lines with the target, then delete the next line:

# For GNU sed (Linux)
sed -i "/$target_word/{n;d}" FILE2.txt

# For BSD sed (macOS, FreeBSD)
sed -i '' "/$target_word/{n;d}" FILE2.txt
  • /target_word/ matches lines containing the target
  • {n;d} tells sed to read the next line (n) and delete it (d)
  • The -i flag edits the file in-place. BSD sed requires an empty suffix (-i '') to avoid creating a backup file; add a suffix like -i.bak if you want to keep a copy of the original.

Important Notes

  • Always backup your FILE2.txt before running these commands (e.g., cp FILE2.txt FILE2.txt.bak)—better safe than sorry if something goes wrong!
  • If your target word contains special regex characters (like ., *, or []), you'll need to escape them first. For example, if the word was camelot., you'd use target_word=$(tail -n1 FILE1.txt | awk '{print $1}' | sed 's/[.*+?^${}()|[\]\\]/\\&/g') to escape special characters.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:01:21