Extract shell part of script file name

In bash, I would like to extract some of the many file names and save this output in another file.

Files are formatted as coffee_ {SOME NUMBERS I WANT} .freqdist.

#!/bin/sh for f in $(find . -name 'coffee*.freqdist) 

This code will find the entire coffee_ file {NOMEBERS i WANT} .freqdist. Now, how do I make an array containing only {SOME NUMBERS, I WANT} and write this to a file?

I know that for writing to a file, one would end the line as follows.

  > log.txt 

I skip the middle part, but how to filter the list of file names.

+4
source share
3 answers

You can do this natively in bash as follows:

 filename=coffee_1234.freqdist tmp=${filename#*_} num=${tmp%.*} echo "$num" 

This is a pure bash solution. No external commands (such as sed ) are involved, so this is faster.

Add these numbers to the file using:

 echo "$num" >> file 

(You will need to delete / clear the file before the start of the loop.)

+9
source

If the goal is simply to write the numbers to a file, you will not need the find command:

 ls coffee*.freqdist coffee112.freqdist coffee12.freqdist coffee234.freqdist 

The following should be done, which can then be redirected to a file:

 $ ls coffee*.freqdist | sed 's/coffee\(.*\)\.freqdist/\1/' 112 12 234 

Guru.

+6
source

The previous answers indicated some necessary methods. This answer organizes the pipeline in a simple way that can be applied to other tasks. (If your sed does not support ', replace'; 'with' sed as a separator.)

 $ ls */c*; ls c* fee/coffee_2343.freqdist coffee_18z8.x.freqdist coffee_512.freqdist coffee_707.freqdist $ find . -name 'coffee*.freqdist' | sed 's/.*coffee_//; s/[.].*//' > outfile $ cat outfile 512 18z8 2343 707 
+1
source

Source: https://habr.com/ru/post/1436134/


All Articles