Lennoard Silva Lennoard Silva - 4 months ago 10
Bash Question

Shell - How can I split a line of text into fragments using SED?

I got a output from a command and it is something like this

2048,4096,8192,16384,24576,32768
.

I want to split it into 6 different files but only the numbers, not the commas e.g
The initial text:
2048,4096,8192,16384,24576,32768
be split into:
2048
to the file A,
4096
to the file B,
8192
to the file C and so on.

That output follows this rules:


  1. There are always 6 spaces, separated by commas

  2. The numbers are always from 3 to 5 "length" (I don't know the proper English word)

  3. As I told you, commas doesn't interest me because I'm going to do mathematical operations with those numbers



I tried to delete the last X numbers but didn't get a way to "detect" a comma so the operation can stop.
Is it possible using SED?

Answer
declare list_of_files=(fileA fileB fileC fileD fileE)
for i in $(sed 's/,/\n/;{;P;D;}' <<< '2048,4096,8192,16384,24576,32768'); do
  echo $i > "${list_of_files["$((num++))"]}"
done

Explanation:

  • s/,/\n/ substitutes every comma with a newline
  • { starts a command group
  • P prints everything in the pattern buffer up to the first newline
  • D Detetes everything in the pattern buffer up to the first newline and then restarts the current command group
  • } ends the command group

EDIT: Let's say you want to copy the information into /system/file but want to have every number in its own row:

$ sed 's/,/\n/;{;P;D;}' < /sys/module/lowmemorykiller/parameters/minfree > /system/file

This will create a new file /system/file that will contain the formatted output.

Comments