3

This question already has an answer here:

I have the following lines

3, 3, 100
4, 2, 50
8, 5, 80
.
.
.

and I want the following output

line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80
.
.
.

I tried the following: sed 's/^/line starts at /' then applying this command for the output: sed 's/, / and ends at /' then applying this command for the output sed 's/, / with value /'. Is there any way to do it in a single line?

marked as duplicate by l0b0, Archemar, Kiwy, Stephen Kitt, Timothy Martin Apr 5 '18 at 0:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I tried the following: sed 's/^/line starts at /' then applying this command for the output: sed 's/, / and ends at /' then applying this command for the output sed 's/, / with value /'. Is there any way to do it in a single line? – Franky Apr 3 '18 at 3:00
12

awk is good for this kind of formatted input - formatted output:

awk -F, '{printf("line starts at %d and ends at %d with value %d\n", $1, $2, $3)}' file 
line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80
  • This is absolutely beautiful! – Franky Apr 4 '18 at 19:27
3

A shell while read loop with printf:

while IFS=', ' read c1 c2 c3; do
    printf 'line starts at %s and ends at %s with value %s\n' \
        "$c1" "$c2" "$c3"
done <file

By setting the IFS variable to a space and a comma, the read command will use those characters as field delimiters.

Output:

line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80
2

It turns out that there is -e option in sed

sed -e 's/^/line starts at /g' -e 's/, / and ends at /' -e 's/, / with value at /'
0

There is a easy and fast way to do this in shell itself:-


# cat f
3, 3, 100
4, 2, 50
8, 5, 80

# cat f | while read line ;  do  IFS=", " array=($line) ; echo "line starts at ${array[0]} and ends at ${array[1]} with value ${array[2]}"; done 

line starts at 3 and ends at 3 with value 100
line starts at 4 and ends at 2 with value 50
line starts at 8 and ends at 5 with value 80

  • 2
    Why not split it up in the read itself instead of doing the extra step of creating an array? – Kusalananda Apr 3 '18 at 9:02
  • I hope you're not actually running this as root… – Kevin Apr 3 '18 at 17:29
  • Oh yes, that is much better – ananTgarg Apr 4 '18 at 11:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.