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

如何在Shell脚本中使用sed命令提取指定字段生成两个输出文件

使用sed处理Test.txt实现两种输出需求

需求说明

  • 输出文件1:每行保留日期时间与文件名
  • 输出文件2:每行仅保留文件名

输入文件Test.txt内容

-rw-r--r--  1 dev dev  93K Sep 18 05:37 Server-23091805496-2-AC.log
-rw-r--r--  1 dev dev  40K Sep 18 05:44 ServerM-23090331-5709-log.log
-rw-r--r--  1 dev dev 484K Sep 18 05:46 Server-280334-12570-log.log
-rw-r--r--  1 dev dev 235K Sep 18 05:47 Server-233405500-1-AC.log

实现命令

1. 生成保留日期时间与文件名的输出文件

使用扩展正则匹配前7组空格分隔的字段(权限、硬链接数、属主、属组、大小等),将其替换为空:

sed -E 's/^([^ ]+ ){7}//' Test.txt > output1.txt

output1.txt预期内容:

Sep 18 05:37 Server-23091805496-2-AC.log
Sep 18 05:44 ServerM-23090331-5709-log.log
Sep 18 05:46 Server-280334-12570-log.log
Sep 18 05:47 Server-233405500-1-AC.log

2. 生成仅保留文件名的输出文件

匹配行首到最后一个空格的所有内容,替换为空,只保留最后一个字段(文件名):

sed 's/.* //' Test.txt > output2.txt

或者用扩展正则捕获最后一个字段并输出:

sed -E 's/^.* ([^ ]+)$/\1/' Test.txt > output2.txt

output2.txt预期内容:

Server-23091805496-2-AC.log
ServerM-23090331-5709-log.log
Server-280334-12570-log.log
Server-233405500-1-AC.log

之前尝试命令的问题说明

  • sed 's/ /\n/g' Test.txt:将所有空格替换为换行,把每行拆分为多个单行,完全不符合需求。
  • ls -ltr | grep "Sep 18 08:" |sed -n '1p'|cut -d ' ' -f2:逻辑错误,是处理ls的输出而非Test.txt,且仅提取第一行的第2个字段,无法批量处理目标文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:00:35