如何移除文件字符串间空格以适配S3 Bucket上传需求?
The problem with your original script is that for i in $(cat test) splits the input by every whitespace (spaces, tabs, newlines), so each word gets processed individually instead of treating each line as a single entry. That's why you end up with each word on its own line after removing spaces.
Here are three simple, effective ways to fix this and remove all spaces from each line in your file:
1. Use a while read Loop (Most Reliable for Line-by-Line Processing)
This method reads each line of the file as a single variable, so spaces within the line are preserved until we remove them:
while IFS= read -r line; do echo "$line" | tr -d ' ' done < test
IFS=ensures leading/trailing spaces are not trimmed from the line.-rprevents backslashes in the line from being interpreted as escape characters.tr -d ' 'deletes all spaces from the entire line.
2. Use sed for a One-Liner
Sed is perfect for text substitution across lines. This command replaces every space in each line with nothing:
sed 's/ //g' test
s/ //gmeans: substitute every occurrence of a space (/ /) with an empty string, globally (gflag) across the entire line.
3. Use awk for Another One-Liner
Awk can also handle this with its gsub (global substitute) function:
awk '{gsub(/ /,""); print}' test
gsub(/ /,"")replaces all spaces in the current line with nothing.printoutputs the modified line.
All three methods will process your input line static2 deploy TDPlanValidator-Prod into static2deployTDPlanValidator-Prod (removing all spaces from the line). If you want to save the output to a new file instead of printing it, just add > output.txt to the end of any of the commands, like:
sed 's/ //g' test > cleaned_test.txt
内容的提问来源于stack exchange,提问作者user6904665

