Finding a certain character in a filename and count the characters up to the certain character

Hello,

I do have folders containing having funny strings in their names and one space.
First, I do remove the funny strings and replace the space by an underscore.

find . -name '* *' | while read file;
do
target=`echo "$file" | sed 's/ /_/g;s/�/ae/g;s/�/Ae/g;s/�/ue/g;s/�/Ue/g;s/�/oe/g;s/�/Oe/g;s/�/ss/g'`;
echo "Renaming '$file' to '$target'";
mv "$file" "$target";
done;

Next step I need to do is storing only the characters up to the underscore in a variable. Problem: the number of characters preceding the underscore varies.
Something like:

Name_FirstName
LastName_Firstname

By using

echo $target | wc -c

I'll get the total number of characters of the folder name. But how can I extract only the characters up to the underscore?

Any help is highly appreciated!

Thanks a lot in advance!

tempestas

echo "Name_Firstname" | cut -d'_' -f1

If you have a modern shell

$ x='Name_Firstname'
$ echo ${x%_*}
Name
1 Like

Thanks a lot. I was close:

echo "Name_Firstname" | cut -d _ 1

tempestas