如何使用awk的gsub去除文件中的./和.txt字符
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.txtwhen 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

