如何在csh中替换set xx {}区间内的指定字符串?
CSH Script to Modify
set xx Block Content Got it, let's tackle this problem. We can use sed (a stream editor perfect for text manipulation) within a csh script to target exactly the lines inside the set xx { \ ... } block and apply the required pattern replacement.
The Script
Save this as modify_set_xx.csh:
#!/bin/csh # Check if input file is provided if ($#argv != 1) then echo "Usage: $0 <input_file_path>" exit 1 endif # Define input and output files set input_file = $1 set output_file = "${input_file}.modified" # Use sed to process the target block sed '/set xx { \\/,/}/ { # Skip the opening and closing lines of the set xx block /set xx { \\/! { /}/! { # Replace pattern: wrap the second-last directory in * and add * at line end s/\(.*\/\)\([^\/]*\)\(\/[^\/]*\) \\/\1*\2*\3* \\/ } } }' $input_file > $output_file echo "Processing done! Modified content saved to: $output_file"
How It Works
- Range Selection: The
sedcommand first targets all lines between/set xx { \\/(the start of your block) and/}/(the end of the block). - Skip Boundary Lines: We exclude the opening
set xx { \line and closing}line from modification. - Pattern Replacement: For each middle line:
\(.*\/\): Captures everything up to the second-last/(e.g.,a/froma/c/d,apple/d/fromapple/d/e/g)\([^\/]*\): Captures the second-last directory name (e.g.,c,e)\(\/[^\/]*\): Captures the last/and directory name (e.g.,/d,/g)- We rewrite the line to wrap the second-last directory in
*and append a*at the end before the trailing\.
How to Use
- Make the script executable:
chmod +x modify_set_xx.csh - Run it with your input file:
./modify_set_xx.csh your_input_file.txt - The modified content will be saved to
your_input_file.txt.modified.
Testing with Your Sample Input
If you run this script on your sample input, it will produce exactly the output you specified—only modifying the lines inside the set xx block while leaving other set commands untouched.
内容的提问来源于stack exchange,提问作者Kin Hwa
相关产品推荐
相关产品推荐

