2

Example:

file1

Speed: 50.00 Temperature: 120.00
Speed: 51.00 Temperature: 121.00
Speed: 52.00 Temperature: 122.00

file2

50.00 120.00
51.00 121.00
52.00 122.00

I want to write file1 to file2

3 Answers3

7
awk '{print $2, $4}' file1 > file2
Peschke
  • 4,148
5

Assuming the fields are separated by a single space:

cut -d" " -f2,4 file1 > file2
glenn jackman
  • 85,964
3

The awk solution is probably the shortest and concise and probably faster on large files but the shell can do that also. Here is one way.

Using bash.

while read -ra line; do
  printf '%s %s\n' "${line[1]}" "${line[3]}"
done < file1 > file2

Bash has -a option for the builtin read which creates an array per line and the while loop will take care of the lines in the file. The only advantage of this solution is that it does not use any external command from the shell. A more portable solution would require a lot PEs.

Abishek J
  • 170
Jetchisel
  • 1,264
  • 2
    By "portable", you probably mean "standard". Bash is portable (runs on most unices), but its read -a is not standard (does not work in most other shells). Not that it matters a great deal though... – Kusalananda Jan 16 '20 at 14:58
  • "Portable" meaning the code will run regardless which shell you use it. That's what POSIX is trying to address (I hope.) You probably mean compatible between bash versions, meaning the code will run even on bashv1 or less... – Jetchisel Jan 16 '20 at 16:21
  • 1
    Yes, that's what Kusalananda explained: this is bash-specific and won't work in POSIX shells because the -a option is non-standard. Try running it in dash, for example, or even bash called as sh. POSIX shells don't support arrays at all. – terdon Jan 16 '20 at 17:00
  • There is no advantage in not using a command designed to do the job and using a shell read loop instead. This will be extremely slow and has other issues. See why-is-using-a-shell-loop-to-process-text-considered-bad-practice – Ed Morton Jan 18 '20 at 02:19
  • I'm not telling that the shell is better that the utility designed to do the job. Did I mention that? All I'm saying is that the shell can do the job also, slower than the other solution? yes indeed. – Jetchisel Jan 18 '20 at 02:43