belo
belo

Reputation: 27

Capture part of name so that I can loop in linux

how do i capture a pattern in a filename and use that to do in linux?

example in a folder contains these files:
BBB137O19_rc.fa BBB921N08_cleaned.fa BBB002O19_cc.fa

I would like to capture the front part of the filename and use that to do things like renaming, run a program etc. Apparently, basename is greedy and works for everything before the extension.

thanks in advance

I tried this command but failed
for i in *.fa; base=$(basename $i _*.fa); comb="${base}_ec.txt"; mv ec.txt $comb; done

Upvotes: 1

Views: 33

Answers (2)

Jakub Pasoń
Jakub Pasoń

Reputation: 231

Also, sed can be used: echo "$i"|sed 's/_.*//'

This removes _ and any character (.) occuring any number of times after it (*). Sed with its regular expressions is especially useful, if you have more complicated patterns to process.

Upvotes: 0

anubhava
anubhava

Reputation: 785481

You can use BASH string manipulations:

s='BBB921N08_cleaned.fa'

echo "${s%%_*}"
BBB921N08

Upvotes: 2

Related Questions