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

如何编写Bash/Python脚本删除文件每行第三个单词后的内容?

Hey there! I've tackled exactly this kind of text processing task before, so here are two straightforward solutions—one using Bash's built-in tools (super fast for text jobs) and another using Python (great for more flexibility):

Bash Solution (Using Awk)

Awk is perfect for this kind of field-based text manipulation since it splits lines into fields by whitespace by default.

Basic Command (Write to New File)

awk '{print $1, $2, $3}' input.txt > output.txt
  • How it works: $1, $2, $3 refer to the first, second, and third "words" (fields) of each line. Printing just these automatically discards everything after the third field.
  • If your input file has lines with fewer than 3 words, this will just print whatever words exist (no errors).

In-Place Modification (Overwrite Original File)

Awk doesn't support direct in-place editing, but you can use a temporary file to achieve this:

awk '{print $1, $2, $3}' input.txt > temp.txt && mv temp.txt input.txt

Python Solution

If you need more control (like handling edge cases or integrating with other Python logic), here's a script that does the job:

One-Liner Quick Fix

For a quick command-line run without writing a full script:

python -c "with open('input.txt') as f: print(' '.join([' '.join(line.split()[:3]) for line in f if line.strip()]))"

This will read all lines, process each to keep only the first 3 words, then join all processed lines into a single line (matching your expected output format).

Full Script (More Flexible)

This script handles edge cases (like lines with fewer than 3 words) and lets you easily adjust behavior:

# Open the input file and read all lines
with open("input.txt", "r") as input_file:
    lines = input_file.readlines()

processed_content = []
for line in lines:
    # Strip whitespace and split into words
    words = line.strip().split()
    # Keep first 3 words, or all if there are fewer
    kept_words = words[:3] if len(words) >=3 else words
    # Join back into a string and add to processed list
    processed_content.append(' '.join(kept_words))

# Write the result to output.txt (or overwrite input.txt if needed)
with open("output.txt", "w") as output_file:
    # Join all processed lines into one line (as per your expected output)
    output_file.write(' '.join(processed_content) + '\n')

Example Verification

If your input file has these lines:

ssessment assay 5.83 8 10 5 6 4 5 7 3
incubate breed 6.40 10 6 10 5 7 4 7 7
incubate develop 7.20 7 7 8 6 7 7 9 10

Both solutions will produce your expected output:

ssessment assay 5.83 incubate breed 6.40 incubate develop 7.20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:04:47