0

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?

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

6 Comments

@mklement thank you for the hint for Mac. I have 0 experience with Mac OS. also I guess OS X sed has no -i either, what is the corresponding option?
-i does exist on OS X - same meaning: edit the file in place (overwrite it with sed's output) - however, there's a crucial difference: to make it work on OS X, use -i '' - the '' means: don't create a copy of the original file; if you wanted to create a copy, say with extension .bak, use -i '.bak'.
@mklement that is to say, the empty string after -i is required. good to know. thx.
Exactly. To summarize: On OS X, in the sed command, use -E instead of -r, and -i '' (must be separate option with empty string as argument) instead of just -i.
The use of an empty string is advised against in the BSD sed man page: It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.
|
1

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..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.