aless80 aless80 - 2 years ago 68
Bash Question

Insert sed in a one liner to strip a string from the filename

This should be an easy question. Using the linux terminal I want to crop images in a folder using convert and change their name using sed. For example,
The following one liner crops the images in a folder as i expect:

for file in Screenshot*.png; do convert -crop 1925x1060+10+1 $file newname_$file; done

However, I want to strip the "Screenshot-" string from the filename. With sed I could use sed -n 's/Screenshot-//p' :

echo "Screenshot-1.png" | sed -n 's/Screenshot\-//p'

But how can I insert sed in the for loop above?

For example, if I have a folder with these images:

Screenshot.png Screenshot-1.png Screenshot-2.png do_not_crop.png

I expect to see these files:

Screenshot.png 1.png 2.png do_not_crop.png

Additional points for who can tell me how to convert Screenshot.png to 0.png

Edit: based on hek2mgl's answer, this script works:

for file in Screen*png;
do convert -crop 1925x1060+10+1 $file
$(if [[ "$file" == "Screenshot.png" ]];
then echo "0.png";
else echo "${file#Screenshot-}";

and outputs 0.png

Answer Source

I would use bash's parameter expansion rather than sed.


for file in Screenshot.png  Screenshot-1.png  Screenshot-2.png  do_not_crop.png ; do
    echo "${file#Screenshot-}"


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download