Sed字符串处理求助:为列表元素添加指定前缀生成目标格式
Got it, let's break down why your original sed command isn't working and fix this properly.
Your sed 's/^/9000/g' file.txt command fails because it just mindlessly inserts "9000" at the start of every line, ignoring the length of the original number:
- The number
1becomes90001(5 digits, not the 4 you need) - The number
13becomes900013(6 digits, way off)
What we actually need to do is format the original number into a 3-digit string with leading zeros, then prepend a 9 to make it 4 digits total (e.g., 1 → 001 → 9001, 13 → 013 → 9013).
Here are two practical approaches to get the desired result:
Method 1: Use sed (pure text replacement)
If you want to stick with sed, you can use regex to match numbers by their digit count and add the correct number of zeros:
sed -E ' s/^([0-9])$/900\1/; # Handle 1-digit numbers: prepend "900" s/^([0-9]{2})$/90\1/; # Handle 2-digit numbers: prepend "90" s/^([0-9]{3})$/9\1/ # Handle 3-digit numbers: prepend "9" (for future compatibility) ' file.txt
-Eenables extended regex for cleaner syntax\1refers to the original number we matched, so we don't lose the original value
Method 2: Use printf (cleaner and more reliable)
printf's formatting capabilities are perfect for this kind of leading-zero task, and the syntax is more straightforward:
while read num; do printf "9%03d\n" "$num" done < file.txt
%03dformats the number into a 3-digit string, adding leading zeros if needed- Adding the
9at the front gives us exactly the 4-digit format you want
Using your sample number list (split into one number per line in file.txt), either command will output:
9001 9001 9013 9005 9014 9004 9001 9005 9012 9007 9008 9009 9004 9018 9003 9020 9011 9017 9013
内容的提问来源于stack exchange,提问作者Pydavide

