Reputation: 91
I'm just learning Bash scripting, and I couldn't quite find an answer on here that worked for me, so here's what I'm trying to do...
I've got file list.txt with contents like this..
group: 43 [message]
group: 312 [message]
group: 501210 [message]
In a bash script, I'm trying to loop through the whole file and fix the formatting as such (delete the colon, leave only one space between 'group' and the number, and ultimately then remove everything after the number):
group 43
group 312
group 501210
It should then be saved to that same file, list.txt, overwriting the previous contents. However, I can't even figure out how to remove the ':'..
Here's my code...
for line in $(< list.txt);do
sed 's/:/""/';
done
It appears to load the first line and then is lost in an infinite loop. Can anyone help?
Upvotes: 0
Views: 5704
Reputation: 9936
Since this is about learning bash scripting you could do:
while read group nr rest
do
printf "%s %d\n" "${group%:}" "$nr"
done < file > newfile && mv newfile file
or if "group" does not vary in the input file:
while read group nr rest
do
printf "group %d\n" "$nr"
done < file > newfile && mv newfile file
But this would typically be slower than using sed
, awk
, etc..
Upvotes: 1
Reputation: 195179
you don't need the for loop. sed one liner could do the job:
sed -ir 's/(group):( [0-9]+).*/\1\2/' list.txt
or the awk one-liner:
awk -F': | ' '{print $1,$2}' list.txt > /tmp/t.tmp && mv /tmp/t.tmp /path/to/list.txt
Upvotes: 3