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

如何使用awk的gsub去除文件中的./和.txt字符

Fixing Your Awk gsub Issue for Stripping ./ and .txt

Ah, I see exactly where your gsub call went wrong! The problem is that you're using a character class ([./txt]) which matches individual characters instead of the exact substrings ./ and .txt you want to remove. Let's break this down and fix it.

Why Your Original Code Fails

[./txt] tells awk to match any single character that's either ., /, t, or x. This means it would strip out the t in file_name too, turning it into fil_name—definitely not what you're aiming for!

Correct Solutions

You need to target the exact substrings you want to remove, anchored to the right parts of the line. Here are two reliable approaches:

Method 1: Two Separate gsub Calls (Most Precise)

Use one gsub to eliminate the leading ./ and another to remove the trailing .txt:

{
  gsub(/^\.\//, "");  # Remove the exact "./" from the start of the line
  gsub(/\.txt$/, ""); # Remove the exact ".txt" from the end of the line
  print
}
  • ^\.\//: The ^ anchors the match to the line start, \. escapes the dot (since it's a special regex character), and \/ escapes the slash.
  • \.txt$: The $ anchors the match to the line end, ensuring we only remove .txt when it's at the very end of the string.

Method 2: Brevity with a Combined Approach

If you prefer a shorter script, you can combine the logic (though splitting into two calls is more readable for others):

{
  gsub(/^\.\//, "") && gsub(/\.txt$/, "")
  print
}

Test It Out

Run this command with your sample input to verify the result:

echo "./file_name.txt|1230" | awk '{gsub(/^\.\//, ""); gsub(/\.txt$/, ""); print}'

You'll get your desired output:

file_name|1230

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:24:28