Tuesday, October 4, 2022

[SOLVED] Remove suffix as well as prefix from path in bash

Issue

I have filepaths of the form:

../healthy_data/F35_HC_532d.dat

I want to extract F35_HC_532d from this. I can remove prefix and suffix from this filename in bash as:

for i in ../healthy_data/*; do echo ${i#../healthy_data/}; done # REMOVES PREFIX

for i in ../healthy_data/*; do echo ${i%.dat}; done # REMOVES SUFFIX

How can I combine these so that in a single command I would be able to remove both and extract only the part that I want?


Solution

If you can use Awk, it is pretty simple,

for i in ../healthy_data/*
do 
    stringNeeded=$(awk -F/ '{split($NF,temp,"."); print temp[1]}' <<<"$i")
    printf "%s\n" "$stringNeeded"
done

The -F/ splits the input string on / character, and $NF represents the last field in the string in that case, F35_HC_532d.dat, now the split() function is called with the de-limiter . to extract the part before the dot.

The options/functions in the above Awk are POSIX compatible.


Also bash does not support nested parameter expansions, you need to modify in two fold steps something like below:-

tempString="${i#*/*/}"
echo "${tempString%.dat}"

In a single-loop,

for i in ../healthy_data/*; do tempString="${i#*/*/}"; echo "${tempString%.dat}" ; done 

The two fold syntax here, "${i#*/*/}" part just stores the F35_HC_532d.dat into the variable tempString and in that variable we are removing the .dat part as "${tempString%.dat}"



Answered By - Inian
Answer Checked By - Gilberto Lyons (WPSolving Admin)