3

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?

1
  • 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? Commented Apr 3, 2018 at 3:00

4 Answers 4

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
1
  • This is absolutely beautiful! Commented Apr 4, 2018 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 /'
3
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

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.