如何在Bash脚本中使用带变量的Awk命令删除文件特定内容
Why Your Awk Variable Usage Isn't Working & How to Fix It
Let's break down what's going wrong with your command and how to adjust it to delete the target text block using a variable.
Key Issues in Your Original Command
- Shell variables aren't automatically available in Awk: When you run
P="Part 2" awk ..., thePvariable is set in the shell environment, but Awk doesn't pick it up unless explicitly told to. - Incorrect variable interpolation in regex: Using
$Pinside a regex literal (/.../) is invalid in Awk. The$symbol in Awk refers to field numbers (like$1for the first field), not variable substitution.
Corrected Awk Commands
Method 1: Pass the variable to Awk with -v
This is the most straightforward approach. Use the -v flag to export the shell variable into Awk, then build your regex pattern using string concatenation with the ~ operator:
P="Part 2" awk -v part="$P" ' $0 ~ "^[#]+(" part " start)[#]+" { f=1 } f && $0 ~ "^[#]+(" part " end)[#]+" { f=0; next } !f' test.txt
Method 2: Access the environment variable directly in Awk
If you prefer to keep the variable in the shell environment, use Awk's ENVIRON array to retrieve its value:
P="Part 2" awk ' $0 ~ "^[#]+(" ENVIRON["P"] " start)[#]+" { f=1 } f && $0 ~ "^[#]+(" ENVIRON["P"] " end)[#]+" { f=0; next } !f' test.txt
How This Works
- The
-v part="$P"flag creates an Awk variablepartwith the value of your shell'sPvariable. - The
~operator checks if the current line ($0) matches the constructed regex pattern. We build the pattern by concatenating thepartvariable with the fixed strings" start"and" end", wrapped in the matching#characters. - The
fflag works exactly as in your original command: it toggles on when we hit the start of the target block, and toggles off (skipping the end line) when we hit the block's end. Lines are only printed whenfis false.
Example Output
Running either corrected command will produce the desired result:
#######################Part 1 start###################### text #######################Part 1 end####################### #######################Part 3 start##################### text #######################Part 3 end#######################
内容的提问来源于stack exchange,提问作者Vincenzo Mangiacapra
相关产品推荐
相关产品推荐

