Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract part of a filename shell script

Tags:

bash

shell

In bash I would like to extract part of many filenames and save that output to another file.

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

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

That code will find all the coffee_{SOME NUMBERS I WANT}.freqdist file. Now, how do I make an array containing just {SOME NUMBERS I WANT} and write that to file?

I know that to write to file one would end the line with the following.

  > log.txt

I'm missing the middle part though of how to filter the list of filenames.

like image 715
mac389 Avatar asked Sep 25 '12 11:09

mac389


People also ask

What is $@ in .sh file?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

How do you read a filename in Unix shell script?

`basename` command is used to read the file name without extension from a directory or file path. Here, NAME can contain the filename or filename with full path.

How do you get 3rd element from each line from a file?

The command designed to retrieve columns from text files is called cut . To get third column in tab delimited file, you can simply call it as cut -f3 <file> . Different delimiter can be passed via -d parameter, e.g.: cut -f3 -d: . You can even get multiple columns, or characters at fixed positions on the line.

What is $_ in shell script?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@


2 Answers

You can do it natively in bash as follows:

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

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

Append these numbers to a file using:

echo "$num" >> file

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

like image 106
dogbane Avatar answered Nov 25 '22 02:11

dogbane


If the intention is just to write the numbers to a file, you do not need find command:

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

The below should do it which can then be re-directed to a file:

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

Guru.

like image 20
Guru Avatar answered Nov 25 '22 04:11

Guru